2013-07-12 101 views
0

我想在TreeView中顯示一些xml數據。 Xml數據由ViewModel的XmlDataProvider類型屬性提供。但是,我無法將其與TreeView綁定。我在XAML中使用XmlDataProvider,無法將ViewModel屬性與XAML中的XmlDataProvider綁定。下面是代碼片段:如何在視圖中使用XmlDataProvider綁定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光框架。當我嘗試時,我得到異常,XDoc屬性應該是靜態的,我不想讓它靜態。

如果定義我的X:XAML文件中的內部XmlDataProvider數據,那麼樹形視圖的工作原理:

<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

[檢查此鏈接] [1]我認爲這將他lp的你.. [1]:http://stackoverflow.com/questions/1017843/how-to-bind-an-xmldataprovider-class-property-to-a-xaml-treeview – loop

+0

鏈接你提到的不是遵循MVVM架構。許多事情在代碼後面完成。 – User1551892

+0

好吧首先設置頁面datacontext到你的mainviewmodel(希望你已經做到了這一點),現在你的treeview可以訪問xdoc屬性 – loop

回答

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

check this link ..in此鏈接,您想成爲顯示樹狀視圖XML數據done..means工作完成..所以只是檢查出來..

相關問題