开发者

Adding to Canvas Programmatically

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

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;
});


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.

0

精彩评论

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

关注公众号