将项目追加到WPF中的数据绑定ItemsControl [英] Append Items to Databound ItemsControl in WPF

查看:255
本文介绍了将项目追加到WPF中的数据绑定ItemsControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组合框,该组合框已数据绑定到项目的ObservableCollection。我想有一个默认的选定项目,即(None),它将我绑定到 SelectedValue的属性的值设置为null。

I've got a Combo Box that is databound to an ObservableCollection of items. I would like to have a default selected item that is (None) that would set the value of the property I've bound to "SelectedValue" to null.

我认为应该有一种通过Style / DataTemplate / TemplateSelector的某种组合来实现这一目标的方法。我试图在设计时考虑MVVM,所以我想要一种不使用代码隐藏且可重复使用的东西。我也希望ObservableCollection的好处(更新集合,使控件重新绑定)保持不变。

I think there ought to be a way to achieve this with some combination of Style/DataTemplate/TemplateSelector. I'm trying to design this with MVVM in mind, so I'd like something that doesn't use codebehind and is as reusable as possible. I'd also like the benefits of the ObservableCollection (updating the collection causing the control to rebind) to remain intact.

B部分奖金:
也可以将额外的可视元素附加到ItemsControl的底部。我当时想,如果我知道如何在集合的最后一项上触发它,那么更改DataTemplate会很容易。愿意在这里接受其他选择。

Bonus part B: I would like to also be able to append an extra visual element to the bottom of an ItemsControl as well. I was thinking it would be easy to change the DataTemplate if I knew how to trigger it on the last item of a collection. Willing to entertain other options here.

推荐答案

我找到的最简单的方法是插入一个特殊值放入基础集合中,并在选中时显示(无)文本。显然,您需要通过转换器运行绑定,以将此值考虑在内,并在选择它时返回null。 (请参阅我的此问题我试图将实际的空值添加到ComboBox的基础集合中。)

The simplest way I've found to do this is to insert a "special" value into the underlying collection, and display the "(None)" text when it's selected. Obviously then you need to run your binding through a converter to take this value into account and return null when it's selected. (See this question of mine which was a result of me trying to add an actual null value to a ComboBox's underlying collection.)

话虽如此,实际上<< a href = http://msdn.microsoft.com/zh-cn/library/system.windows.data.compositecollection.aspx rel = nofollow noreferrer> CompositeCollection 类。您可以创建一个单独的集合(只有一个项目-空项目),然后通过CompositeCollection将ComboBox绑定到它和原始集合。

Having said that, it might actually be possible to do what you want with the CompositeCollection class. You could make a separate collection (with only one item - your Null item) and bind your ComboBox to both it and your original collection through the CompositeCollection.

这篇关于将项目追加到WPF中的数据绑定ItemsControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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