我想使用 XML 文档的数据绑定来填充一个简单的表单,该表单显示有关人员列表的详细信息。我现在已经完成了所有设置和工作:
<Window x:Class="DataBindingSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Window.Resources>
<XmlDataProvider x:Key="xmlProvider" XPath="People" Source="c:\someuri.xml"/>
</Window.Resources>
<Grid>
<ListBox Name="personList" ItemsSource="{Binding Source={StaticResource xmlProvider}, XPath=Person}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding XPath=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<GroupBox Header="GroupBox" Name="groupBox1" DataContext="{Binding ElementName=personList, Path=SelectedItem}">
<Grid>
<TextBox Name="nameText" Text="{Binding XPath=Name}"/>
<ComboBox Name="genderCombo" Text="{Binding XPath=Gender}">
<ComboBoxItem>Male</ComboBoxItem>
<ComboBoxItem>Female</ComboBoxItem>
</ComboBox>
</Grid>
</GroupBox>
</Grid>
</Window>
(为清楚起见,所有位置/布局元素已被删除)
现在这很好用!如果我为它提供一些与提供的路径匹配的 XML,我会在列表框中获得一个名称列表,单击时在相应字段中显示名称和性别。当我开始尝试在我的 XML 源中使用命名空间时,问题就出现了。XAML 然后更改为如下所示:
<Window x:Class="DataBindingSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Window.Resources>
<XmlNamespaceMappingCollection x:Key="namespaceMappings">
<XmlNamespaceMapping Uri="http://www.mynamespace.com" Prefix="mns"/>
</XmlNamespaceMappingCollection>
<XmlDataProvider x:Key="xmlProvider" XmlNamespaceManager="{StaticResource namespaceMappings}" XPath="mns:People" Source="c:\someuriwithnamespaces.xml"/>
</Window.Resources>
<Grid>
<ListBox Name="personList" ItemsSource="{Binding Source={StaticResource xmlProvider}, XPath=mns:Person}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding XPath=mns:Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<GroupBox Header="GroupBox" Name="groupBox1" DataContext="{Binding ElementName=personList, Path=SelectedItem}">
<Grid>
<TextBox Name="nameText" Text="{Binding XPath=mns:Name}"/>
<ComboBox Name="genderCombo" Text="{Binding XPath=mns:Gender}">
<ComboBoxItem>Male</ComboBoxItem>
<ComboBoxItem>Female</ComboBoxItem>
</ComboBox>
</Grid>
</GroupBox>
</Grid>
</Window>
使用此代码(当然还有适当命名空间的 xml),列表框仍能正确显示名称,但单击这些名称不再更新名称和性别字段!我的怀疑是 xml 命名空间以某种方式对 groupbox 的 DataContext 做出了不利的反应,但我不确定为什么或如何。有谁知道如何在这种情况下使用 XML 命名空间?