动态更改ComboBox的DisplayMemberPath?

时间:2016-11-23 20:09:00

标签: c# wpf xaml data-binding combobox

假设我想用一个简单的Employee对象列表填充ComboBox ...

public class Employee
{
    private int ID { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public string Project { get; set; }

}

然后像这样通过XAML绑定该列表......

            <ComboBox ItemsSource="{Binding EmployeeList}"
                      SelectedValue="{Binding SelectedEmployee}"
                      DisplayMemberPath="Project"/>

现在我可以使用此ComboBox查找并按项目选择员工记录。但是,如果员工当前没有与他们相关联的项目,我还希望能够根据名称或部门查找记录(使用相同的ComboBox和绑定)。关于如何实现可以像上面描述的那样更改DisplayMemberPath值的任何想法?

1 个答案:

答案 0 :(得分:0)

DisplayMemberPath只是a string property。在viewmodel中绑定到它。

<ComboBox ...
   DisplayMemberPath="{Binding DispMemberPath}"
/>

...视图模型

private string _DispMemberPath;
public string DispMemberPath
{ 
  get {return _DispMemberPath; }
  set { _DispMemberPath= value; RaiseNotifyPropertyChanged(); }
}

private void SetDepartmentAsPath()
{
    this.DispMemberPath = "Department";
}
相关问题