2010-12-14 51 views
1

我有一個窗口,裏面有一個樹視圖控件和一個XML文件。我想將樹視圖綁定到完全來自XAML的XML文件,而沒有任何C#代碼。如何將XML綁定到沒有代碼的TreeView(MVVM,來自XAML的dataContext)

這是我正在做的現在:

XAML

<Window.Resources> 
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TreeViewItemData"> 
     <TreeViewItem Header="{Binding Path=Attribute[text].Value}" IsExpanded="True"/> 
    </HierarchicalDataTemplate> 
</Window.Resources> 
<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="40" /> 
     <RowDefinition Height="370*" /> 
    </Grid.RowDefinitions> 
    <TextBlock Text="RD Admin Tool" Grid.Row="0" FontSize="22" FontWeight="Bold" Padding="50,5"></TextBlock> 
    <StackPanel Orientation="Horizontal" Grid.Row ="1"> 
     <Border BorderBrush="#FF7C7B7B" BorderThickness="1" Name="tBorder" Width="200" CornerRadius="5" Background="#FFF5F2F2"> 
      <TreeView Name="OptionsTree" 
         ItemsSource="{Binding Path=Root.Elements}" 
         ItemTemplate="{StaticResource TreeViewItemData}" 
         HorizontalAlignment="Left" VerticalAlignment="Top" 
         Margin="5,0,0,0" FontSize="18" Background="#FFF5F2F2"> 
      </TreeView> 
     </Border> 
     <Canvas Name="OptionContent" Width="445"> 
     </Canvas> 
    </StackPanel> 
</Grid> 

構造在後面的代碼

public MyWindow() 
    { 
     InitializeComponent(); 

     XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\Tree.xml")); 
     this.MyTreeView.DataContext = doc; 
    } 

但我真的很想寫它來自XAML並且沒有代碼。

有什麼建議嗎?

回答

2

您可以使用XAML中的XmlDataProvider將外部XML定義爲資源。這可以被引用並綁定到XAML中的各種元素中。

漫步,可以發現here ......除了一個MSDN樣品使得結合使用XmlDataProvider的一個TreeViewhere

+0

打我吧! :) – 2010-12-14 20:25:58

+0

@Stuart我們至少有不同的鏈接...所有都沒有徒然... :) – 2010-12-14 20:28:16

+0

夥計們,感謝您的反饋,但我試圖讓它與TreeView一起工作,它顯示空(沒有節點)。你能舉出一些代碼示例嗎?再次感謝 – 2010-12-14 21:40:18