如何将一个通用项目添加到绑定到WPF中的集合的ComboBox [英] How do you add a generic item to a ComboBox bound to a collection in WPF

查看:341
本文介绍了如何将一个通用项目添加到绑定到WPF中的集合的ComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个WPF应用程序中绑定到C#ViewModel类中的部门对象的ObservableCollection的ComboBox。我想使用组合框按部门过滤另一个集合(确实它的工作原理)问题是,我想添加一个额外的选项全部到列表的顶部。有正确的方法来做到这一点。

I have a ComboBox in a WPF application that is bound to an ObservableCollection of Department objects in a C# ViewModel class. I want to use the combo box to filter another collection by department (And indeed it works for that now) The problem is that I want to add an additional option "All" to the top of the list. Is there a correct way to do this. Making a fake department feels wrong in so many ways.

ComboBox

<ComboBox ItemsSource="{Binding Path=Departments}" 
          SelectedValue="{Binding Path=DepartmentToShow , Mode=TwoWay}" />


推荐答案

您可以使用 CompositeCollection 作为ComboBox的ItemsSource包含全部选项。您需要将CollectionContainer的Collection属性设置为您的Department对象的ObservableCollection。

You could use a CompositeCollection as the ItemsSource for the ComboBox to include the "All" option. You need to set the Collection property of the CollectionContainer to your "ObservableCollection of Department objects".

<ComboBox >
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem>All</ComboBoxItem>
            <CollectionContainer x:Name="departmentCollection"/>
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

不知道这是否适合您的过滤情况...

Not sure if this will be suitable for your filtering situation however...

这篇关于如何将一个通用项目添加到绑定到WPF中的集合的ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆