行为中的 Lambda 表达式委托
我有一个在列表框中使用的附加行为,如果列表仅包含一个元素,它应该自动选择列表中的第一个元素。
我发现在列表更改时挂钩列表框的唯一方法是使用列表框的 itemcollections CollectionChanged 事件:
private static void ListenToItemsCollectionChange(ListBox listBox)
{
var collection = (INotifyCollectionChanged)listBox.Items;
collection.CollectionChanged += (sender, args) => SelectAndSetFocusToFirstElement(listBox);
}
现在的问题是,无法取消订阅该事件,这可能会导致多次调用 <代码>SelectAndSetFocusToFirstelement()。
对此的正常解决方案是不使用 lambda。但随后我会丢失我的列表框,我需要它来选择第一个元素。
关于如何解决这个问题有什么建议吗?
I have an attached behavior that used on a listbox, it should automatically select the first element in the list, if the list contains only one element.
The only way that I have found to hook the listbox when the list changes, is to use the listbox' itemcollections CollectionChanged event:
private static void ListenToItemsCollectionChange(ListBox listBox)
{
var collection = (INotifyCollectionChanged)listBox.Items;
collection.CollectionChanged += (sender, args) => SelectAndSetFocusToFirstElement(listBox);
}
The problem now, is that there is no way of unsubscribing from the event, which potentially leads to multiple invokations of SelectAndSetFocusToFirstelement( )
.
The normal solution to this, is to not use lambdas. But then I would loose my listbox, which I need for selecting the first element.
Any suggestions on how this can be solved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Lambda 只是委托的快捷方式,因此您可以重写 lambda,然后
您可以将更改事件添加到集合中
并删除
A Lambda is just a shortcut for a delegate, so you can rewrite the lambda as
then you can add to the collection changed event
and remove
我有点困惑你所说的“但是我会失去我的列表框”是什么意思?
也许这个解决方案就足够了
您可以将事件处理程序保留在临时变量中
,如果您想取消订阅您可以使用 -= handler
I got a little bit confused what do You meand by "But then I would loose my listbox" ?
Maybe this solution will be sufficient
You could keep the event handler in temporary variable like that
and if You want to unsubscribe You could use -= handler