开发者

Lambda expression delegates in behavior

开发者 https://www.devze.com 2023-03-15 08:32 出处:网络
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.

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) => SelectAndSetFocusToFirstEle开发者_JAVA百科ment(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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消