我希望使用数据绑定来填充一个简单的表单,显示有关一组人员的详细信息。目前,我已经将其全部设置好并运行如下:
<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),ListBox仍然正确显示名称,但是点击这些名称不再更新名称和性别字段!我怀疑某种方式xml命名空间对GroupBox的DataContext产生了不良反应,但我不确定为什么或如何解决。有人知道如何在这种情况下使用XML命名空间吗?