1
大家好,WPF XML数据绑定到组合框
我尝试使用下面的代码绑定一些XML转换为组合框:
<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 [email protected]}" 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 [email protected]}"
HorizontalContentAlignment="Stretch" Height="23" />
</UserControl>
该项目建立不错,我可以看到填充组合框按预期。然而,当我试图让在代码隐藏我得到的是空/空字符串选定值:
string compName = this.LocationCombo.SelectedValuePath.ToString();
MessageBox.Show(compName);
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>
你没有得到'SelectedValue',你得到'SelectedValuePath'。如果你使用'SelectedValue',我不知道这会起作用 - 我总是最终使用'SelectedItem',正如karmicpuppet所暗示的那样 - 但是'SelectedValuePath'永远不会让你获得选定的值。 – 2010-08-30 16:20:09