【问题标题】:Dynamically change the DisplayMemberPath of a ComboBox?动态更改组合框的 DisplayMemberPath?
【发布时间】:2016-11-23 20:09:00
【问题描述】:

假设我想用简单的 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 值的任何想法,就像我在上面描述的那样?

【问题讨论】:

    标签: c# wpf xaml data-binding combobox


    【解决方案1】:

    DisplayMemberPath 只是 a string property。在您的视图模型中绑定到它。

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

    视图模型...

    private string _DispMemberPath;
    public string DispMemberPath
    { 
      get {return _DispMemberPath; }
      set { _DispMemberPath= value; RaiseNotifyPropertyChanged(); }
    }
    
    private void SetDepartmentAsPath()
    {
        this.DispMemberPath = "Department";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      相关资源
      最近更新 更多