与 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
Confused with wpf ComboBox DisplayMemberPath,SelectedValue and SelectedValuePath
提问by user451259
I have always struggled with those comboBox properties
我一直在为那些 comboBox 属性而苦恼
- DisplayMemberPath
- SelectedValue
- SelectedValuePath
- 显示成员路径
- 选定值
- 选定值路径
I am building a master detail form .
我正在构建一个主详细信息表单。
- ComboBox filled with Customers
- User Selects a Customer in Combo
- All the textBoxes EG Fills correctly
- 装满客户的 ComboBox
- 用户在组合中选择客户
- 所有文本框 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"/>
DisplayMemberPath
points to the Name
property, so the value displayed in the ComboBox
and the Employee
entries contained in the drop down list, will be the Name
property of the Employee
object.
DisplayMemberPath
指向Name
属性,因此显示在下拉列表中的值ComboBox
和Employee
包含在下拉列表中的条目将是对象的Name
属性Employee
。
To understand the other two, you should first understand SelectedItem
. SelectedItem
will return the currently selected Employee
object from the ComboBox
. You can also assign SelectedItem
with an Employee
object to set the current selection in the ComboBox
.
要了解其他两个,您应该首先了解SelectedItem
. SelectedItem
将从中返回当前选定的Employee
对象ComboBox
。您还可以SelectedItem
使用Employee
对象进行分配以设置ComboBox
.
SelectedValuePath
points to Id
, which means you can get the Id
of currently selected Employee
by using SelectedValue
. You can also set the currently selected Employee
in the ComboBox
by setting the SelectedValue
to an Id
(which we assume will be present in the Employees
list).
SelectedValuePath
点Id
,这意味着你可以得到Id
当前选择的Employee
使用SelectedValue
。您还可以通过将 设置为 an (我们假设它将出现在列表中)来设置当前选定Employee
的。ComboBox
SelectedValue
Id
Employees