WPF XML Databind to ComboBox
HI All,
I am trying to bind some XML into a combobox using the below code:
<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>
The project builds fine and i can see the ComboBox populated as expected. however, when i try to get the selected value in the code-behind all i get is an empty/null string:
string compName = this.LocationCombo.SelectedValuePath.ToString();
MessageBox.Show(compName);
the xml file looks like below:
<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>
Try getting the ComboBox.SelectedItem property, cast it to an XmlNode, and use that instead. Something like this:
XmlNode element = this.LocationCombo.SelectedItem as XmlNode;
MessageBox.Show(element.Attributes["LCode"].Value.ToString() + element.InnerText.ToString());
精彩评论