views:

158

answers:

2

Is there a way to translate this code in VB? Most of it is easy, but I can't figure out a way to override the event handler.

public class MTObservableCollection<T> : ObservableCollection<T>
{

    public MTObservableCollection()
    {
        _DispatcherPriority = DispatcherPriority.DataBind;
    }
    public MTObservableCollection(DispatcherPriority dispatcherPriority)
    {
        _DispatcherPriority = dispatcherPriority;
    }
    private DispatcherPriority _DispatcherPriority;

    public override event NotifyCollectionChangedEventHandler CollectionChanged;
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        var eh = CollectionChanged;
        if (eh != null)
        {
            Dispatcher dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()
                                     let dpo = nh.Target as DispatcherObject
                                     where dpo != null
                                     select dpo.Dispatcher).FirstOrDefault();

            if (dispatcher != null && dispatcher.CheckAccess() == false)
            {
                dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => OnCollectionChanged(e)));
            }
            else
            {
                foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
                    nh.Invoke(this, e);
            }
        }
    }

}
+2  A: 

Rewrite Edit:

A conversation that figures it's a compiler implementation snafu and suggests workarounds:

http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/ce30ceed-c260-4d99-b96d-5b7179466be8

This is my (semi) final answer.

John K
Code that can't possibly compile isn't much use to me. The line "Public Overloads Overrides Event CollectionChanged As NotifyCollectionChangedEventHandler" is not valid VB syntax.
Jonathan Allen
Can you tell I don't do much VB. You're correct my original answer wouldn't compile so I have replaced it with something else instead of deleting altogether.
John K
Thanks, that was a rather interesting discussion.
Jonathan Allen
+1  A: 

It is even an error to override events in C#. The C# Programming Guide says:

Do not declare virtual events in a base class and override them in a derived class. The C# compiler does not handle these correctly in Microsoft Visual Studio 2008 and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event.

I wonder why a framework class breaks this rule, or even why the compiler allows it.

Wilhelm
WPF is a strange beast and does a lot of things that don't make much sense.
Jonathan Allen