TwoWay手动绑定实现ListBox.SelectedItems? [英] TwoWay Manual Binding Implementation for ListBox.SelectedItems?
问题描述
我一直在试图看看是否有一个简单/聪明的方法来实现绑定到ListBox.SelectedItems。如果您尝试过自己,您将知道,使用BindingExtension的标记绑定将无法正常工作 - 该属性不支持它。所以你要配置一个用于SelectionChanged并尝试该路由的处理程序。我最接近的是这篇文章:
I've been trying to see if there is an easy/clever way to implement binding to ListBox.SelectedItems. If you have tried yourself, you will know, that markup binding using BindingExtension will not work - the property doesn't support it. So you are left with wiring up a handler for SelectionChanged and trying that route. The closest I've gotten is this post:
http://alexshed.spaces.live.com/blog/cns!71C72270309CE838!149.entry
http://alexshed.spaces.live.com/blog/cns!71C72270309CE838!149.entry
更新:上述博客不再可用,该作者的当前博客在这里,最接近我参考的博客文章是此StackOverflow答案。
Update: the above mentioned blog is no longer available, that author's current blog is here and the closest I could find to the referenced blog post is this StackOverflow answer.
它在一个方便的附加属性中实现了所有必需的C#。但它实现了约束力作为单向目标来源。我想要双向绑定。
Which implements all the necessary C# in a handy attached property. But it implements the "binding" as a One-Way, Target to Source. I'd like Two-Way binding.
任何想法?
推荐答案
p>我发现了一个优雅的解决方案,我刚刚找到时间写一个关于它的博文。
I've found an elegant solution, and I've just found time to write a blog post about it.
我所做的是创建一个附加属性,可以在ListBox(或DataGrid实际上)上设置的SynchronizedSelectedItems)。你将它数据绑定到一个集合,然后,有一点魔法,ListBox上的SelectedItems属性和你的集合保持同步。您可以从我的博客文章中下载所有代码。
What I did was to create an attached property, SynchronizedSelectedItems that you can set on the ListBox (or DataGrid in fact). You databind this to a collection, and then, with a bit of magic, the SelectedItems property on the ListBox and your collection are kept in sync. You can download all the code from my blog post.
魔术是在两个集合中侦听CollectionChanged事件的类,并将更改传播到另一个。
The "magic" is a class which listens out for CollectionChanged events in either collection, and propagates the changes to the other.
这篇关于TwoWay手动绑定实现ListBox.SelectedItems?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!