行为中的 Lambda 表达式委托

发布于 2024-11-17 03:56:03 字数 632 浏览 0 评论 0原文

我有一个在列表框中使用的附加行为,如果列表仅包含一个元素,它应该自动选择列表中的第一个元素。

我发现在列表更改时挂钩列表框的唯一方法是使用列表框的 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?

Full code

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雪若未夕 2024-11-24 03:56:03

Lambda 只是委托的快捷方式,因此您可以重写 lambda,然后

NotifyCollectionChangedEventArgs collectionChangedDelegate = (sender, arg) =>
{SelectAndSetFocusToFirstElement(listBox)};

您可以将更改事件添加到集合中

collection.CollectionChanged += collectionChangedDelegate

并删除

collection.CollectionChanged -= collectionChangedDelegate

A Lambda is just a shortcut for a delegate, so you can rewrite the lambda as

NotifyCollectionChangedEventArgs collectionChangedDelegate = (sender, arg) =>
{SelectAndSetFocusToFirstElement(listBox)};

then you can add to the collection changed event

collection.CollectionChanged += collectionChangedDelegate

and remove

collection.CollectionChanged -= collectionChangedDelegate
喜你已久 2024-11-24 03:56:03

我有点困惑你所说的“但是我会失去我的列表框”是什么意思?

也许这个解决方案就足够了

您可以将事件处理程序保留在临时变量中

  EventHandler handler = (a, b) => { }; // You must use aproperiate delegate
    collection.CollectionChanged += handler

,如果您想取消订阅您可以使用 -= 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

  EventHandler handler = (a, b) => { }; // You must use aproperiate delegate
    collection.CollectionChanged += handler

and if You want to unsubscribe You could use -= handler

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文