与 wpf ComboBox DisplayMemberPath、 SelectedValue 和 SelectedValuePath 混淆

我一直在纠结于那些 comboBox 属性

  1. DisplayMemberPath
  2. SelectedValue
  3. SelectedValuePath

我正在构建一个主细节表单。

  1. 充满客户的组合框
  2. 用户在组合中选择客户
  3. 正确填写所有文本框

我的问题是,我已经使它工作,但我不明白这些性质和差异。 有没有一个简单的例子来解释他们是做什么的?

59345 次浏览

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:

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

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.

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