如何在绑定wpf后将项目插入组合框

Gee*_*eth 2 wpf combobox

我想在绑定后将项目添加到组合框中.例如:

this.cbCategory.ItemsSource = categoryList;
        this.cbCategory.DisplayMemberPath = "CategoryName";
        this.cbCategory.SelectedValuePath = "CategoryID";
Run Code Online (Sandbox Code Playgroud)

我想添加("全部","%")作为第一个.

格塔.

Ray*_*rns 9

使用CompositeCollection非常简单:

<ComboBox DisplayMemberPath="CategoryName" SelectedValuePath="CategoryID">
  <ComboBox.ItemsSource>
    <CompositeCollection>
      <my:Item CategoryName="All" CategoryID="%" />
      <CollectionContainer Collection="{Binding CategoryList}" />
    </CompositeCollection>
  </ComboBox.ItemsSource>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

工作原理:CompositeCollection生成"All"项,后跟CategoryList集合中的所有项.请注意,这<my:Item ... />是项类的构造函数.您需要将其更改为实际的命名空间和类名.

重要建议:我注意到你在代码隐藏中设置了一些ComboBox属性.这是一个非常糟糕的做法.您应该使用如上所示的XAML.