我是WPF的新手。 我有一个组合框绑定到Window.Resources中定义的XML数据源。
组合框值显示在设计器中,但它在运行时显示为空。
我在这里遗漏了什么。
<Window x:Class="WpfExample4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<XmlDataProvider x:Key="xmlData">
<x:XData>
<customers>
<customer name="Customer 1">
<order desc="Big Order">
<orderDetail product="Glue" quantity="21" />
<orderDetail product="Fudge" quantity="32" />
</order>
</customer>
<customer name="Customer 2">
<order desc="First Order">
<orderDetail product="Mousetrap" quantity="4" />
</order>
</customer>
</customers>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid DataContext= "{Binding Source={StaticResource xmlData}, XPath=customers/customer}" Margin="4" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<!-- CUSTOMERS -->
<DockPanel Grid.Row="0">
<TextBlock DockPanel.Dock="Top" FontWeight="Bold" Text="Customers" />
<ComboBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding XPath=@name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</DockPanel>
</Grid>
</Window>
答案 0 :(得分:0)
您应该将命名空间添加到根元素(msdn)。
注意:的
XML数据的根节点具有设置XML的xmlns属性 命名空间为空字符串。这是应用XPath的要求 查询XAML页面内联的数据岛。在这 内联案例,XAML,以及数据岛,继承了 System.Windows命名空间。因此,您需要设置 命名空白,以防止XPath查询被限定 System.Windows命名空间,它会误导查询。
...
<Window.Resources>
<XmlDataProvider x:Key="xmlData">
<x:XData>
<customers xmlns="">
<customer name="Customer 1">
<order desc="Big Order">
<orderDetail product="Glue" quantity="21" />
<orderDetail product="Fudge" quantity="32" />
</order>
</customer>
...