2010-08-30 2 views
1

HI Tous,WPF XML Databind à ComboBox

Je suis en train de lier certains XML dans un combobox utilisant le code ci-dessous:

 <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> 

Le projet se construit bien et je peux voir le ComboBox comme prévu . Cependant, lorsque je tente d'obtenir la valeur sélectionnée dans le i obtenir le code-behind tout est une chaîne vide/null:

string compName = this.LocationCombo.SelectedValuePath.ToString(); 
       MessageBox.Show(compName); 

le fichier xml ressemble ci-dessous:

<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

Vous n'obtenez pas 'SelectedValue', vous obtenez le' SelectedValuePath'. Je ne sais pas si cela fonctionnera si vous utilisez 'SelectedValue' - j'ai toujours utilisé' SelectedItem', comme le suggère karmicpuppet - mais 'SelectedValuePath' ne vous apportera jamais la valeur sélectionnée. –

Répondre

2

Essayez d'obtenir ComboBox Propriété .SelectedItem, affectez-la à un XmlNode et utilisez-la à la place. Quelque chose comme ceci:

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