ListBox.SelectedItems 的双向手动绑定实现? [英] TwoWay Manual Binding Implementation for ListBox.SelectedItems?

查看:25
本文介绍了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

更新:上述博客不再可用,该作者当前的博客是在这里,我能找到的与引用的博客文章最接近的是this StackOverflow answer.

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.

有什么想法吗?

推荐答案

我找到了一个优雅的解决方案,我刚好有时间写一个 关于它的博文.

I've found an elegant solution, and I've just found time to write a blog post about it.

我所做的是创建一个附加属性 SynchronizedSelectedItems,您可以在 ListBox(实际上是 DataGrid)上设置它.您将它数据绑定到一个集合,然后,通过一点魔术,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.

这篇关于ListBox.SelectedItems 的双向手动绑定实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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