How to bind XML to a TreeView without code behind for (MVVM, dataContext from XAML)
I have a window with a tree view control inside and a XML file. I want to bind the tree view to the XML file entirely from the XAML, without any C# code behind.
This is how I'm doing it now:
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>
<Ro开发者_高级运维wDefinition 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>
Constructor in code behind:
public MyWindow()
{
InitializeComponent();
XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\Tree.xml"));
this.MyTreeView.DataContext = doc;
}
But I'd really like to write it from the XAML and have no code behind.
Any suggestion?
You can make use of the XmlDataProvider
within XAML to define your external XML as a resource. This can then be referenced and bound to within your various elements in XAML.
Walk through can be found here...in addition an MSDN sample makes use of the XmlDataProvider
in conjunction with a TreeView
here
You can use XmlDataProvider to specify the xml data source and then bind to that.
This article discusses the technique: http://msdn.microsoft.com/en-us/magazine/cc163299.aspx
精彩评论