rudeboy rudeboy - 3 months ago 22
C# Question

Dynamically change the DisplayMemberPath of a ComboBox?

Say I want to fill a ComboBox with a list of simple Employee objects...

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


and then bind that list through XAML like this...

<ComboBox ItemsSource="{Binding EmployeeList}"
SelectedValue="{Binding SelectedEmployee}"

Now I can use this ComboBox to look up and select Employee records by Project. But if an Employee doesn't currently have a Project associated to them I would also like the ability to look up records (using the same ComboBox and bindings) by Name or Department if I so choose. Any ideas on how would I implement something that will make changes to the DisplayMemberPath value like I described above?


DisplayMemberPath is just a string property. Bind to it in your viewmodel.

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


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

private void SetDepartmentAsPath()
    this.DispMemberPath = "Department";