我试图在TreeView中显示一些xml数据。 Xml数据由ViewModel的XmlDataProvider类型的属性提供。但是,我无法将其与TreeView绑定。我在XAML中使用XmlDataProvider,无法在XAML中将ViewModel属性与XmlDataProvider绑定。以下是代码段:
public class MainViewModel : ViewModelBase {
private static XmlDataProvider xDoc;
public static XmlDataProvider XDoc {
get {
return xDoc;
}
set {
xDoc = value;
RaisePropertyChanged( "XDoc" );
}
}
public MainViewModel( ) {
Data d = new Data( );
d.int1 = 12;
d.int2 = 20;
d.str = "Hello World";
XmlSerializer serializer = new XmlSerializer( d.GetType( ) );
StringWriter strWriter = new StringWriter( );
serializer.Serialize( strWriter, d );
XDoc = new XmlDataProvider { Document =XDocument.Parse( strWriter.ToString( ) ).ToXmlDocument (), XPath="child::node"} ;
}
}
Xaml代码:
<XmlDataProvider x:Key="xmlDP" Source="{ x:Static A:MainViewModel.XDoc}" XPath="">
</XmlDataProvider>
<TreeView Grid.Row="2" Grid.ColumnSpan="2" Name="xmlTree"
DataContext="{StaticResource xmlDP}" ItemsSource="{Binding}" ItemTemplate="{StaticResource treeViewTemplate}"/>
我正在使用mvvm light框架。当我尝试时,我得到异常,XDoc属性应该是静态的,我不想让它静态。
如果在xaml文件中的XmlDataProvider中定义我的X:数据,那么treeview可以工作:
<XmlDataProvider x:Key="xmlDP" XPath="">
<x:XData>
<Employees>
<Employee Name="Steven Ballmer" DOB="1-Mar-1956">
<Title>CEO</Title>
</Employee>
</Employees>
</x:XData>
</XmlDataProvider>
<TreeView Grid.Row="2" Grid.ColumnSpan="2" Name="xmlTree"
DataContext="{StaticResource xmlDP}" ItemsSource="{Binding}" ItemTemplate=" {StaticResource treeViewTemplate}"/>
答案 0 :(得分:0)
check this link ..在这个链接中你想要完成的工作..在树视图中显示xml数据已完成..所以只是检查出来..
答案 1 :(得分:0)
如果我不使用XMLDataProvider并仅使用XMLDoxument,那么一切正常:
public class MainViewModel : ViewModelBase {
private XmlDocument xDoc;
public XmlDocument XDoc {
get {
return xDoc;
}
set {
xDoc = value;
RaisePropertyChanged( "XDoc" );
}
}
public MainViewModel( ) {
Data d = new Data( );
d.int1 = 12;
d.int2 = 20;
d.str = "Hello World";
XmlSerializer serializer = new XmlSerializer( d.GetType( ) );
StringWriter strWriter = new StringWriter( );
serializer.Serialize( strWriter, d );
XDoc = XDocument.Parse( strWriter.ToString( ) ).ToXmlDocument () ;
}
}
<TreeView Grid.Row="2" Grid.ColumnSpan="2" Name="xmlTree"
ItemsSource="{Binding XDoc}" ItemTemplate="{StaticResource treeViewTemplate}"/>