简体   繁体   English

清除Canvas中具有依赖项属性的UserControl

[英]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. 我在运行时生成了许多UserControl (带有少量标签的网格)并将其添加到Canvas I have implemented drag-and-drop for each UserControl and node line (or connector line) between UserControls. 我已经为UserControl和UserControl之间的节点线(或连接器线)实现了拖放。

When I clear the UserControl with myCanvas.Children.Clear() , I received the following error in method Node_LayoutUpdated() : 当我使用myCanvas.Children.Clear()清除UserControl时,在Node_LayoutUpdated()方法中收到以下错误:

在此处输入图片说明

This is my UserControl: 这是我的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? 我应该在删除UserControl之前先删除DependencyProperty,如何? 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. 在删除(清除)Canvas的子级之后,将立即调用LayoutUpdated事件。 TransformToVisual doesn't work if the Control is already detached from the VisualTree. 如果控件已经从VisualTree中分离出来,则TransformToVisual不起作用。 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 . 一个快速的解决方法是在Clear之前分离控件。

Add this code to your UserControl: 将此代码添加到您的UserControl中:

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

And this to your MainWindow: 这到您的MainWindow:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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