C#在Template中创建ObservableCollection <t>

时间:2017-05-16 05:51:57

标签: wpf xaml combobox observablecollection visual-studio-2017

我正在尝试使用Combobox,它可以显示2个类, - 员工 - 雇主 显然,这两个类都有EditAble变量

  private ObservableCollection<Employer> _itemsEmployer
  private ObservableCollection<Employee> _itemsEmployee
  public ObservableCollection<T>  Items, where T : Employee, Employer
    {
        get
        {
            return _itemsEmployee;
        }

        set
        {
            if (_itemsEmployee == value)
            {
                return;
            }

            _itemsEmployee = value;
        }
    }

Combobox:

<ComboBox x:Name="cbx" 
                      IsTextSearchEnabled="True" 
                      TextSearch.Text="EditAble"
                      ItemsSource="{Binding Items}" IsEditable="True" 
                      DisplayMemberPath="EditAble"
                      Text="{Binding AddedText,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" 
                      Canvas.Left="78" Canvas.Top="48" Width="259">

1 个答案:

答案 0 :(得分:0)

属性无法定义通用约束。你需要有一个Employee和Employer的基类 - 例如人。这样,该集合可以同时容纳员工和雇主。

private ObservableCollection<Person> _persons = new ObservableCollection<Person>();

public ObservableCollection<Person> Items
{
    get
    {
        return _persons;
    }

    set
    {
        if (value == _persons)
        {
            return;
        }

        _persons = value;
    }
}