简体   繁体   English

WPF组合框的选定值不显示

[英]selected value of WPF combobox does not display

I have an xml file as follows :- 我有一个xml文件,如下所示:

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

and I have a WPF combobox :- 我有一个WPF组合框:

<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. 您似乎对使用ComboBox选择选项有些困惑。 I would advise you to read the How to: Use SelectedValue, SelectedValuePath, and SelectedItem page at MSDN for help. 我建议您阅读MSDN上的“ 如何:使用SelectedValue,SelectedValuePath和SelectedItem”页以寻求帮助。 There are a number of ways to make selection in a ComboBox , all of which are clearly described in the linked article. ComboBox进行选择的方法有很多,链接的文章中都对这些方法进行了明确说明。

From MSDN: 从MSDN:

DisplayMemberPath: Gets or sets a path to a value on the source object to serve as the visual representation of the object. DisplayMemberPath:获取或设置源对象上的值的路径,以用作对象的视觉表示。

SelectedValue: Gets or sets the value of the SelectedItem, obtained by using SelectedValuePath. SelectedValue:获取或设置通过使用SelectedValuePath获得的SelectedItem的值。

SelectedValuePath: Gets or sets the path that is used to get the SelectedValue from the SelectedItem. SelectedValuePath:获取或设置用于从SelectedItem获取SelectedValue的路径。

SelectedItem: Gets or sets the first item in the current selection or returns null if the selection is empty SelectedItem:获取或设置当前选择中的第一项;如果选择为空,则返回null

Also, why are you setting the same properties in code and in XAML? 另外,为什么还要在代码 XAML中设置相同的属性?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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