C# WPF XML数据绑定到组合框
大家好 我尝试使用以下代码将一些XML绑定到组合框中:C# WPF XML数据绑定到组合框,c#,wpf,xml,data-binding,xaml,C#,Wpf,Xml,Data Binding,Xaml,大家好 我尝试使用以下代码将一些XML绑定到组合框中: <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="myComboBoxControl"> <UserControl.Resou
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="myComboBoxControl">
<UserControl.Resources>
<DataTemplate x:Key="dataTemplateNode">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="20"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding XPath=@LCode}" Grid.Column="0" Margin="5,0,0,0" FontWeight="Bold"/>
<TextBlock Text="{Binding XPath=.}" Grid.Column="1"/>
</Grid>
</DataTemplate>
<XmlDataProvider x:Key="xmlNodeList" Source="/data/LocationCodes.xml" XPath="/LocationCodes/Location"/>
</UserControl.Resources>
<ComboBox Name="LocationCombo"
ItemsSource="{Binding Source={StaticResource xmlNodeList}}"
ItemTemplate="{StaticResource dataTemplateNode}"
SelectedValue="{Binding XPath=@LCode}"
HorizontalContentAlignment="Stretch" Height="23" />
</UserControl>
xml文件如下所示:
<LocationCodes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Location LCode="ABD1W">Aberdeen</Location>
<Location LCode="ATH1W">Athens</Location>
</LocationCodes>
香港仔
雅典
尝试获取ComboBox.SelectedItem属性,将其强制转换为XmlNode,然后改用它。大概是这样的:
XmlNode element = this.LocationCombo.SelectedItem as XmlNode;
MessageBox.Show(element.Attributes["LCode"].Value.ToString() + element.InnerText.ToString());
您得到的不是
SelectedValue
,而是SelectedValuePath
。如果您使用SelectedValue
,我不知道这是否有效-正如karmicpuppet所建议的那样,我总是使用SelectedItem
,但是SelectedValuePath
永远无法为您获取所选值。
XmlNode element = this.LocationCombo.SelectedItem as XmlNode;
MessageBox.Show(element.Attributes["LCode"].Value.ToString() + element.InnerText.ToString());