0

我有一个用例,我需要将 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”元素?在这方面有哪些最佳实践?

非常感谢。

4

1 回答 1

0

对不起,如果我误会了你,但是

  • 如果您需要从像 xmlns="..." 这样的默认命名空间访问元素,您应该使用像 Path=Attribute[name].Value 这样的常规语法

  • 如果你有带有前缀命名空间的 XML,比如 xmlns:ns="..." 和这个命名空间中的元素比如 ,你可以尝试使用 Path=Elements["ns:book"]

希望这可以帮助。

于 2010-06-23T21:59:37.653 回答