Creating the TryFindResource Extension Method

Let's imagine that you want to add functionality to a class, but you cannot modify this class. For example, you want to add the functionality TryFindResource to every FrameworkElement (as in WPF). In .NET 3.5 and Silverlight, you can do this with so-called Extension Methods, with the following steps:

1. In the SilverlightUtility project, in the Extensions class, add the method shown in Listing 24.18:

LISTING 24.18 TryFindResource Method public static object TryFindResource(this FrameworkElement element, object resourceKey)

return null;

2. The first parameter of this method is a FrameworkElement marked with the keyword this. The compiler "adds" this method to any instance of the FrameworkElement class it finds in this application. The effect is just as if the method had been defined on the FrameworkElement class.

3. We add the TryFindResource method to the FrameworkElement class, because a look in the WPF documentation reveals that this is where the method is defined in the .NET framework. We want to be as compatible as we can. msdn.microsoft.com/en-">http://msdn.microsoft.com/en-

us/library/system.windows.frameworkelement.tryfindresource.aspx.

4. The method's signature is also compatible with the one defined in the full .NET framework (apart from the this parameter, of course).

If you compile the application now, you see that it builds. The extension method has been recognized and extends the FrameworkElement's functionality.

5. Set the project SilverlightUtility.Test to the StartUp project and run the application now (do not run it in the debugger, but with Ctrl+F5). You see the Silverlight unit test framework window, and your test should fail (see Figure 24.5).

Test run is complete

FIGURE 24.5 Silverlight unit test failed

[iHlMl'TfcTiM Wl)*

FIGURE 24.5 Silverlight unit test failed

Creating Unit Tests for Silverlight 545

0 0

Post a comment

  • Receive news updates via email from this site