如何将视图模型的XmlDataProvider属性与视图中的XmlDataPProvider绑定



我正在尝试在TreeView中显示一些xml数据。Xml数据由类型为XmlDataProvider的ViewModel属性提供。但是,我无法将其与TreeView绑定。我在XAML中使用XmlDataProvider,无法将ViewModel属性与XAML中的XmlDataProvide绑定。以下是代码片段:

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轻型框架。当我尝试时,我得到一个异常,即XDoc属性应该是静态的,并且我不想使它成为静态的。

如果在xaml文件中的XmlDataProvider中定义我的X:data,则树视图有效:

 <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}"/>

如果我不使用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}"/>

相关内容

  • 没有找到相关文章

最新更新