2010-08-30 231 views
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> 
+2

你沒有得到'SelectedValue',你得到'SelectedValuePath'。如果你使用'SelectedValue',我不知道這會起作用 - 我總是最終使用'SelectedItem',正如karmicpuppet所暗示的那樣 - 但是'SelectedValuePath'永遠不會讓你獲得選定的值。 – 2010-08-30 16:20:09

回答

2

嘗試獲得組合框.SelectedItem屬性,將其轉換爲XmlNode,然後使用它。像這樣的:

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