Create data objects from Xaml file
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:Wp开发者_JAVA百科fApplication1">
<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.
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.
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; }
}
精彩评论