WPF 组合框,在绑定到 Observable 集合时添加所有选项项 [英] WPF combo box, adding an all options item, when binding to an Observable Collection

查看:36
本文介绍了WPF 组合框,在绑定到 Observable 集合时添加所有选项项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个具有可观察集合的对象.我绑定到这个集合的大多数地方我只希望用户选择一个项目.但在一个地方,我希望组合框包含所有项目选项.

So I've got an object that has an observable collection. Most places I bind to this collection I only want the user to select a single item. But in one place I want the combobox to include an all items option.

是否可以简单地使用 xaml 转换器来做到这一点?

Is the way to do this simply with xaml converter?

似乎在视图模型中执行此操作是个好主意,但实际上有很多依赖对象 goop 基本上连接了一个集合,该集合是两个对象深的 on change 事件,而 xaml 转换器仅起作用.

It seems like doing it in the view model would be a good idea, but it's really a lot dependency object goop to basically wire up an collection that is two objects deep for an on change event, where as the xaml converter just works.

但我总觉得 xaml 转换器应该是通用的和可重用的,在这种情况下,xaml 转换器更像是一个.

But I always feel like xaml converters should be generic and reusable, where in this instance, the xaml converter would be more of a one off.

当然,第三种选择是在包含标准 observable 集合的对象中为 UI 创建一个关闭列表.但这似乎以一种让我不舒服的方式混合了逻辑和表现.

Of course the third option would be to create one off list for UI in the object that contains the standard observable collection. But this seems to be mixing the logic and presentation in a way that makes me uncomfortable.

推荐答案

查看 复合集合.它允许您将多个集合连接成一个集合——类似于 LINQ 连接.它实现了 INotifyCollectionChanged,所以如果它的一些内部集合是 ObservableCollections,它应该能够对变化做出反应.

Take a look at CompositeCollection. It lets you concatenate multiple collections into a single collection -- sort of the XAML equivalent of the LINQ Concat. It implements INotifyCollectionChanged, so it should be able to react to changes if some of its inner collections are ObservableCollections.

CompositeCollection 还允许您添加单个元素,因此您甚至不需要将所有项目"包装在它自己的集合中.(相反,您必须将集合包装在 CollectionContainer 中.请参阅 CompositeCollection 文档页面上的示例.)

CompositeCollection also lets you add individual elements, so you wouldn't even need to wrap your "All Items" in a collection of its own. (Instead, you have to wrap collections in a CollectionContainer. See the examples on the CompositeCollection doc page.)

这篇关于WPF 组合框,在绑定到 Observable 集合时添加所有选项项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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