与 wpf ComboBox DisplayMemberPath、SelectedValue 和 SelectedValuePath 混淆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3797034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:09:31  来源:igfitidea点击:

Confused with wpf ComboBox DisplayMemberPath,SelectedValue and SelectedValuePath

wpf

提问by user451259

I have always struggled with those comboBox properties

我一直在为那些 comboBox 属性而苦恼

  1. DisplayMemberPath
  2. SelectedValue
  3. SelectedValuePath
  1. 显示成员路径
  2. 选定值
  3. 选定值路径

I am building a master detail form .

我正在构建一个主详细信息表单。

  1. ComboBox filled with Customers
  2. User Selects a Customer in Combo
  3. All the textBoxes EG Fills correctly
  1. 装满客户的 ComboBox
  2. 用户在组合中选择客户
  3. 所有文本框 EG 正确填充

The problem I am having I have made it work but I don't understand those properties and the differences. Is there a noddy example explaining what they do?

我遇到的问题我已经让它工作了,但我不明白这些属性和差异。有没有一个解释他们做什么的例子?

回答by Yogesh

I think we can understand this better with an example. See this class:

我想我们可以通过一个例子更好地理解这一点。看到这个类:

public class Employee
{
   public int Id { get; set; }
   public string Name { get; set; }
}

and the following xaml:

以及以下 xaml:

<ComboBox ItemsSource="{Binding Source={StaticResource Employees}}"
          DisplayMemberPath="Name"
          SelectedValuePath="Id"/>

DisplayMemberPathpoints to the Nameproperty, so the value displayed in the ComboBoxand the Employeeentries contained in the drop down list, will be the Nameproperty of the Employeeobject.

DisplayMemberPath指向Name属性,因此显示在下拉列表中的值ComboBoxEmployee包含在下拉列表中的条目将是对象的Name属性Employee

To understand the other two, you should first understand SelectedItem. SelectedItemwill return the currently selected Employeeobject from the ComboBox. You can also assign SelectedItemwith an Employeeobject to set the current selection in the ComboBox.

要了解其他两个,您应该首先了解SelectedItem. SelectedItem将从中返回当前选定的Employee对象ComboBox。您还可以SelectedItem使用Employee对象进行分配以设置ComboBox.

SelectedValuePathpoints to Id, which means you can get the Idof currently selected Employeeby using SelectedValue. You can also set the currently selected Employeein the ComboBoxby setting the SelectedValueto an Id(which we assume will be present in the Employeeslist).

SelectedValuePathId,这意味着你可以得到Id当前选择的Employee使用SelectedValue。您还可以通过将 设置为 an (我们假设它将出现在列表中)来设置当前选定Employee的。ComboBoxSelectedValueIdEmployees