Hello again,
I have a use-case where I need to bind data from an XML file to a WPF DataGrid. I prepared this example to demonstrate what I'll be doing in my final code.
This is Books.xml:
<?xml version="1.0" encoding="utf-8" ?>
<library>
<books>
<book id="1" name="The First Book" author="First Author">
First Book Content
</book>
<book id="2" name="The Second Book" author="Second Author">
Second Book Content
</book>
</books>
</library>
And here is how I bind it my DataGrid control. First XAML:
<Window x:Class="LinqToXmlBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Window1" Height="300" Width="400">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="268*" />
<ColumnDefinition Width="110*" />
</Grid.ColumnDefinitions>
<toolkit:DataGrid Name="xmlBoundDataGrid" Margin="1" ItemsSource="{Binding Path=Elements[book]}">
<toolkit:DataGrid.Columns>
<toolkit:DataGridTextColumn Header="Book ID" Binding="{Binding Path=Attribute[id].Value}"/>
<toolkit:DataGridTextColumn Header="Book Name" Binding="{Binding Path=Attribute[name].Value}"/>
<toolkit:DataGridTextColumn Header="Content" Binding="{Binding Path=Value}"/>
</toolkit:DataGrid.Columns>
</toolkit:DataGrid>
<StackPanel Name="myStackPanel" Grid.Column="1">
<Button Name="bindToXmlButton" Click="bindToXmlButton_Click">Bind To XML</Button>
</StackPanel>
</Grid>
</Window>
Then, C# code:
const string _xmlFilePath = "..//..//Books.xml";
private void bindToXmlButton_Click(object sender, RoutedEventArgs e)
{
XElement books = XElement.Load(_xmlFilePath).Element(myNameSpace + "books");
xmlBoundDataGrid.DataContext = books;
}
Now, if I defined an XML namespace at the root element of Books.XML to be http://my.namespace.com/books
; I know I can get that namespace programmatically like so:
XNamespace myNameSpace = XElement.Load(_xmlFilePath).Attribute("xmlns").Value;
But, how can I retrieve this namespace in XAML in order to access the "book" element? And what are the best practices in that regard?
Thank you very much.