views:

30

answers:

1

I've got code that adds a custom usercontrol to a canvas. I originally had it in the MouseRightButtonDown event of the Canvas but have since moved it to a collection changed event that fires off in a ViewModel. When I call the exact same method from the CollectionChanged event, the UI does not update to reflect the UserControl on the canvas. However, when I use the exact same code from a mouse event on the canvas, it works beautifully as intended.

I have done some digging and tried the following to fix things to no avail:

  1. Calling the UpdateLayout method of the Canvas

  2. Toggling Visibility properties to try to update the UI.

  3. Invoking it using the UserControl's Dispatcher to invoke an anonymous delegate: Dispatcher.BeginInvoke(()=> code);

Here is an example of the code that I am using:

        CustomUserControl stub = new CustomUserControl();
        stub.Width = 10;
        stub.Height = 10;
        stub.SetValue(Canvas.LeftProperty, xCurrent);
        stub.SetValue(Canvas.TopProperty, yCurrent);

        stub.MouseLeftButtonDown += this.Element_MouseLeftButtonDown;
        stub.MouseMove += this.Element_MouseMove;
        stub.MouseLeftButtonUp += this.Element_MouseLeftButtonUp;

        this.Dispatcher.BeginInvoke(() =>
        {
            drawCanvas.Children.Add(stub);
            drawCanvas.Visibility = Visibility.Visible;
            this.Visibility = Visibility.Visible;
        });
A: 

It is possible that the collectonChanged event is happening before the canvas has been initalized. Try added stuff to the collection after the usercontrol that the canvas lives in has been loaded.

zachary