tags:

views:

33

answers:

2

Currently I am trying to load some Xaml files to create testdata.

I used the Xaml files to create data for the WPF designer in Visual Studio (DesignData). Now I want to reuse them in my Unit Tests. I need to load them somehow programmatically. Here is a small test program:

// The data model
class TestItem
{
    public string Name { get; set; }
    public decimal Value { get; set; }
    public string Category { get; set; }
}

The Xaml data file:

<sys:ArrayList xmlns:sys="clr-namespace:System.Collections;assembly=mscorlib"
               xmlns:local="clr-namespace:WpfApplication1">
  <local:TestItem Name="Item1" Value="123" Category="Cat1" />
  <local:TestItem Name="Item2" Value="456" Category="Cat1" />
  <local:TestItem Name="Item3" Value="789" Category="Cat2" />
</sys:ArrayList>

And now I try to read the data:

var reader = new System.Windows.Markup.XamlReader();

var obj = reader.LoadAsync(File.OpenRead("Test.xaml"));

The LoadAsync method throws an XamlParseException.

'Cannot create unknown type '{clr-namespace:WpfApplication1}TestItem'

Do I need to register my TestItem class somehow? Is this the right approach to solve my problem, or am I missusing XamlReader here? I also spent some time in the System.Xaml-Namespace. But I couldn't get it working.

Edit:

In the sample code above I have set the Build Action to None. When I set it to DesignData the file cannot be found.

+1  A: 

I believe that your approach should work fine.

You mention that you're reusing the same code to write unit tests (which is where you get the exception, if I understand it correctly). If you're writing tests and loading the XAML in other assembly than the one where TestItem is defined, then you'll need to specify the assembly name in the xmlns:local attribute.

Tomas Petricek
I created the above sample code in one assembly. The xmlns:local is set to the correct namespace. I have set the build action of the Xaml file to None (see my update). Still doesnt work.
PetPaulsen
A: 

I found the error. Making the TestItem class public solved my problem.

// The data model
public class TestItem
{
    public string Name { get; set; }
    public decimal Value { get; set; }
    public string Category { get; set; }
}
PetPaulsen