Yet another blog about WPF, Surface, SL, MVVM, NUI....





Tag - .NET4.0

Entries feed - Comments feed


WPF tip : How can I use static/dynamic resources in my tests

24 September 2010

You are surely, as I am, creating a lot of units tests in your WPF applications.

Some of the tests may use statics or dynamics resources declared in your application and when you launch the tests, all you get is an XamlParseException exception thrown.

System.Windows.Markup.XamlParseException: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '11' and line position '83'.
---> System.Exception: Cannot find resource named 'myStaticResource'. Resource names are case sensitive.

The tip to make them work is quite simple to use. What is actually happening ? : the created control is looking for the resource via the classic russian puppets system and does not find the application because the tests does not create it. And the application is exactly where you have declared the needed ressources. So all we've got to do is to create the application and initialize it before running the tests.

Also we called the InitializeComponent() methods to make sure the application is initialized. It seems that this last part is only necessary if the resources are from the same assembly than the application.

So just add this method to your tests classes :

/// <summary>
///Use ClassInitialize to run code before running the first test in the class
/// </summary>
/// <param name="testContext">The test context.</param>
public static void MyClassInitialize(TestContext testContext)
  //Create the application for resources.
  if (System.Windows.Application.Current == null)
    App application = new App();

The App.xaml content is below:

<Application x:Class="MyAssembly.App" xmlns=""
      <myLib:ViewModelLocator x:Key="myStaticResource" />

Here we are !

Shout it kick it on

.NET Framework 4, Windows Applications Development

24 June 2010

I am now certified " .NET Framework 4, Windows Applications Development".

I passed the certification during the beta process and the results are out. I can now use this nice logo anywhere ^^ :