WPF XML Databind到ComboBox

时间:2010-08-30 13:23:56

标签: 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.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>

项目构建正常,我可以看到ComboBox按预期填充。但是,当我尝试在代码隐藏中获取所选值时,我得到的是一个空/空字符串:

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>

1 个答案:

答案 0 :(得分:2)

尝试获取ComboBox.SelectedItem属性,将其强制转换为XmlNode,然后使用它。像这样:

XmlNode element = this.LocationCombo.SelectedItem as XmlNode;
MessageBox.Show(element.Attributes["LCode"].Value.ToString() + element.InnerText.ToString());