如何将XML与命名空间绑定到WPF DataGrid?

时间:2010-06-23 21:50:50

标签: wpf linq-to-xml wpfdatagrid xml-binding

我有一个用例,我需要将XML文件中的数据绑定到WPF DataGrid。我准备了这个例子来演示我将在最终代码中做些什么。

这是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>

以下是我将DataGrid控件绑定到的方式。第一个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>

然后,C#代码:


const string _xmlFilePath = "..//..//Books.xml";
private void bindToXmlButton_Click(object sender, RoutedEventArgs e)
{
     XElement books = XElement.Load(_xmlFilePath).Element(myNameSpace + "books");
     xmlBoundDataGrid.DataContext = books;
}

现在,如果我在Books.XML的根元素中将XML名称空间定义为http://my.namespace.com/books;我知道我可以通过编程方式获得该命名空间:


XNamespace myNameSpace = XElement.Load(_xmlFilePath).Attribute("xmlns").Value;

但是,如何在XAML中检索此命名空间以访问“book”元素?那方面的最佳做法是什么?

非常感谢。

1 个答案:

答案 0 :(得分:0)

对不起,如果我弄错了,但是

  • 如果您需要访问默认命名空间中的元素,例如xmlns =“...”,则应使用常规语法,如Path = Attribute [name] .Value

  • 如果您的XML带有带前缀的命名空间,例如xmlns:ns =“...”和此命名空间中的元素,您可以尝试使用Path = Elements [“ns:book”]

希望这有帮助。

相关问题