在我的应用程序中我有这段代码:
<Grid Name="BaseGrid">
<Grid.Resources>
<XmlDataProvider x:Name="ScenesXmlName" x:Key="ScenesXml" XPath="person" Source="myXml.xml"/>
</Grid.Resources>
<ComboBox Grid.Column="0" Name="ScenariCombo" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource ScenesXml}}" DisplayMemberPath="@name" />
</Grid>
假设我的xml是:
<person name="John">
<address>Some adress here</address>
<work>Some work</work>
</person>
我打算在选择更改时更新多个用户控件。
问题是ComboBox.SelectedItem不是自定义对象,而是一个XmlNode,因为Combobox绑定到XmlDataSource。
您将如何访问内部节点,即:SelectedItem项的地址?
答案 0 :(得分:3)
我为你建立了一个小例子。它有效,但我相信你可以做得更好。
我的Xaml文件:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid Name="BaseGrid">
<Grid.Resources>
<XmlDataProvider x:Name="ScenesXmlName" x:Key="ScenesXml" XPath="person" Source="myXml.xml"/>
<src:Xml2AdressConverter x:Key="Xml2AdressConv"/>
</Grid.Resources>
<ComboBox Name="ScenariCombo" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource ScenesXml}}" DisplayMemberPath="@name" Margin="0,0,272,264" />
<Label Content="Address" Height="28" HorizontalAlignment="Left" Margin="12,110,0,0" Name="label1" VerticalAlignment="Top" Width="87" />
<Label Content="Work" Height="28" HorizontalAlignment="Left" Margin="12,144,0,0" Name="label2" VerticalAlignment="Top" Width="87" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="134,115,0,0" Name="AddressTbx" VerticalAlignment="Top" Width="332"
Text="{Binding ElementName=ScenariCombo, Path=SelectedItem, Converter={StaticResource Xml2AdressConv}, ConverterParameter=address}"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="134,149,0,0" Name="WorkTbx" VerticalAlignment="Top" Width="332"
Text="{Binding ElementName=ScenariCombo, Path=SelectedItem, Converter={StaticResource Xml2AdressConv}, ConverterParameter=work}"/>
</Grid>
我的Xml2AddressConverter类
class Xml2AdressConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
XmlElement xmlElt = value as XmlElement;
if (xmlElt != null)
{
string str, attName;
XElement xElt;
attName = parameter as string;
xElt= XElement.Load(xmlElt.CreateNavigator().ReadSubtree());
str = "";
foreach (XElement x in xElt.Descendants(attName))
{
str = x.Value;
}
return str;
}
return "";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
看看this它显示了如何使用LINQ to XML从xml内容查询数据。