简体   繁体   中英

Clear UserControl with Dependency Property in Canvas

I have a number of UserControl (a Grid with few Labels) being generated and added to Canvas in runtime. I have implemented drag-and-drop for each UserControl and node line (or connector line) between UserControls.

When I clear the UserControl with myCanvas.Children.Clear() , I received the following error in method Node_LayoutUpdated() :

在此处输入图片说明

This is my UserControl:

public partial class Foo : UserControl
{
    public static readonly DependencyProperty AnchorPointProperty =
             DependencyProperty.Register(
            "AnchorPoint", typeof(Point), typeof(Foo),
                new FrameworkPropertyMetadata(new Point(0, 0),
                FrameworkPropertyMetadataOptions.AffectsMeasure));

    public Point AnchorPoint
    {
        get { return (Point)GetValue(AnchorPointProperty); }
        set { SetValue(AnchorPointProperty, value); }
    }

    private Canvas mCanvas;

    public Foo(Canvas canvas, bool isInput)
    {
        InitializeComponent();
        mCanvas = canvas;
        this.LayoutUpdated += Node_LayoutUpdated;
    }

    void Node_LayoutUpdated(object sender, EventArgs e)
    {
        Size size = RenderSize;
        Point ofs = new Point(size.Width / 2, size.Height / 2);
        AnchorPoint = TransformToVisual(this.mCanvas).Transform(ofs);
    }
}

Am I supposed to remove the DependencyProperty before removing the UserControl, and how? Can someone please explain what causes this error message and why?

You problem is the last line of your code. The LayoutUpdated event is invoked right after you remove (Clear) the children of the Canvas. TransformToVisual doesn't work if the Control is already detached from the VisualTree. Subscribing to parent layout events is usually neither required nor a good idea. A quick workaround would be to detach the control before the Clear .

Add this code to your UserControl:

public void Detach()
{    
    this.LayoutUpdated -= Node_LayoutUpdated;
}

And this to your MainWindow:

foreach(WhateverYourControlTypeIs control in myCanvas.Children)
{
    control.Detach();
}
myCanvas.Children.Clear();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM