在Canvas中使用依赖项属性清除UserControl

时间:2016-08-31 06:18:22

标签: c# wpf

我生成了许多 UserControl (一个标签很少的网格)并在运行时添加到 Canvas 。我已经为UserControls之间的每个UserControl和节点行(或连接线)实现了拖放。

当我使用 myCanvas.Children.Clear()清除UserControl时,我在方法 Node_LayoutUpdated()中收到以下错误:

enter image description here

这是我的UserControl:

First try to get list from table like 

1. suppose you have Users Controller and you are trying to show select option in add.ctp  then create

///in UsersController.php

function add(){

 $users = $this->Users->find('list', array('fields' => array('id','first_name'));

  $this->set(compact('users'));

 }

//in Template/Users/add.ctp (cakephp version 3) , in View/Users/add.ctp


echo $this->Form->input('Users.user_id',array(
        'options' => $users`enter code here`
    )); 

// when $users return an empty array this input become input type text otherwise it will be select option

我是否应该在删除UserControl之前删除DependencyProperty,以及如何删除?有人可以解释导致此错误消息的原因以及原因吗?

1 个答案:

答案 0 :(得分:1)

您的问题是代码的最后一行。删除(清除)画布的子项后立即调用LayoutUpdated事件。如果Control已经从VisualTree中分离,则TransformToVisual不起作用。订阅父布局事件通常既不需要也不是好主意。一个快速的解决方法是在Clear之前分离控件。

将此代码添加到UserControl:

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

这是你的MainWindow:

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