【问题标题】:How to bind XML with namespace to WPF DataGrid?如何将带有命名空间的 XML 绑定到 WPF DataGrid?
【发布时间】:2010-06-23 21:50:50
【问题描述】:

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

非常感谢。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    希望这会有所帮助。

    【讨论】:

    • 这会有所帮助,但 XAML 不接受带有类似引号的“ns:book”。删除引号会导致抛出异常。根据你的想法,我也玩了一些东西,但没有运气。不过谢谢你,如果你有更多的想法,请与我分享。
    • 非常感谢您的帮助。
    猜你喜欢
    • 2014-10-23
    • 2011-08-27
    • 2011-01-13
    • 2011-05-14
    • 1970-01-01
    • 2012-02-23
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多