简体   繁体   中英

selected value of WPF combobox does not display

I have an xml file as follows :-

<Root>
   <Level>
       <id>1</id>
       <display>Level1</display>
   </Level>
   <Level>
       <id>2</id>
       <display>Level2</display>
   </Level>
</Root>

and I have a WPF combobox :-

<ComboBox x:Name="cmbLevel" HorizontalAlignment="Left" Margin="73,73,0,0" VerticalAlignment="Top" Width="120"
       SelectedValuePath="id" SelectedValue="{Binding XPath=/Root/Level/id}" 
       ItemsSource="{Binding XPath=/Root/Level}"
       IsSynchronizedWithCurrentItem="True" />

The insert and display works well, however the problem is when I want to populate this combobox with a selected value.

At the moment I have the following

private void InitCombo(XDocument xdoc, ComboBox comboBox, string NodeName)
{
    var displayItems = from ele in xdoc.Descendants(NodeName)
    select new
    {
         id = (string)ele.Element("id"),
         display = (string)ele.Element("display")
    };            

    comboBox.DisplayMemberPath = "display";
    comboBox.SelectedValuePath = "id";
    comboBox.ItemsSource = displayItems.ToList();
 }

and then I am adding the selected value as follows:

cmbLevel.SelectedValue = level;

Do I need to add anything else for it to show the selected value in my combobox? Do I need to rebind the combobox?

Thanks for your help and time

You seem to be somewhat confused about using the ComboBox selection options. I would advise you to read the How to: Use SelectedValue, SelectedValuePath, and SelectedItem page at MSDN for help. There are a number of ways to make selection in a ComboBox , all of which are clearly described in the linked article.

From MSDN:

DisplayMemberPath: Gets or sets a path to a value on the source object to serve as the visual representation of the object.

SelectedValue: Gets or sets the value of the SelectedItem, obtained by using SelectedValuePath.

SelectedValuePath: Gets or sets the path that is used to get the SelectedValue from the SelectedItem.

SelectedItem: Gets or sets the first item in the current selection or returns null if the selection is empty

Also, why are you setting the same properties in code and in XAML?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM