Extending My

One of the most interesting features of the My namespace is that it is extensible with custom members. You can both extend My at the root level or extend existing members such as Application and Computer. The first goal of this section is to show how you can extend My at the higher level, implementing functionalities for working with collections, such as a property that allows converting from a generic collection into an ObservableCollection(Of T). We need to mimic how Visual Basic 2010 handles the My namespace, so first add a new module to the project and name it MyCollectionsUtils. Each member you want to be added to My must start with the My letters; this is the reason for using the MyCollectionsUtils identifier. The compiler can then distinguish that this member belongs to My if you enclose it within such a namespace. Add a reference to the WindowsBase.dll assembly (not required in WPF applications) and then write the code shown in Listing 20.2.

Listing 20.2 Extending My at Root Level

image

Friend Visibility

Module’s members are marked as Friend to reproduce the default Visual Basic behavior.

There are some tasks to perform after examining Listing 20.2. First, notice how the ObservableCollectionHelper class exposes a public method that effectively converts an ICollection(Of T) into a new ObservableCollection. Also notice how there is the need to explicitly provide a Namespace My..End Namespace declaration, which encloses custom members for My. The MyCollectionsUtils module exposes members that are effectively accessible via My. To replicate the VB default behavior, the module is marked as System.Diagnostics.NonUserCode so that the debugger does not step into such code (if you instead need debugger support, simply remove this attribute) and as Microsoft.VisualBasic.HideModuleName that prevents the module name to be shown by IntelliSense when invoking your custom members. Then notice how the helper field is of type ThreadSafeObjectProvider(Of T). According to the Microsoft documentation, this is a best practice because it ensures that each thread invoking My.CollectionsUtils has access to a separate instance. The read-only property CollectionsUtils then wraps the ObservableCollectionHelper.ConvertToObservableCollection method exposing through the GetInstance invocation. When you have created your extension, you can use it in a simple way. The following code shows how you can convert a List(Of Integer) into an ObservableCollection using your custom My.CollectionsUtils member:

image

After seeing how you can extend My at the root level, let’s now see how you can customize existing members.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.240.185