如何在Canvas WPF中删除/删除ContentControl

本文关键字:删除 ContentControl WPF Canvas | 更新日期: 2023-09-27 18:17:57

我从WPF开始,我有一个问题。请帮帮我。谢谢,抱歉我的英语不好!

我已经添加了ContentControl到画布,我想删除它。

绘制ContentControl代码:

ContentControl cc = new ContentControl();
cc.Content = shape;
cc.Height = h;
cc.Width = w;
Style s = myCanvas.FindResource("DesignerItemStyle") as Style;
cc.Style = s;
Canvas.SetLeft(cc, x);
Canvas.SetTop(cc, y);
myCanvas.Children.Add(cc); 

我使用HitTest来删除它,但我只能删除形状

 private void myCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        Point pt = e.GetPosition((Canvas)sender);
        HitTestResult result = VisualTreeHelper.HitTest(myCanvas, pt);            
        if (result != null)
        {
            myCanvas.Children.Remove(result.VisualHit as Shape); //it works with shape  
            // i have changed it into  myCanvas.Children.Remove(result.VisualHit as ContentControl); 
             //but it didn't work with ContentControl           
        }
    }  

如何在Canvas WPF中删除/删除ContentControl

这是因为ContentControlShape的父结点,而Canvas的子结点包含承载该形状的ContentControl。你可以这样做来解决你的问题:)

private void myCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    DependencyObject ob = FindAncestor<ContentControl>((DependencyObject)e.Source);
    if (ob.GetType() == typeof(ContentControl))
            myCanvas.Children.Remove(ob as ContentControl);           
}
public T FindAncestor<T>(DependencyObject dependencyObject)
        where T : DependencyObject
    {
        var parent = VisualTreeHelper.GetParent(dependencyObject);
        if (parent == null) return null;
        var parentT = parent as T;
        return parentT ?? FindAncestor<T>(parent);
    }

我建议你下一个解决方案:

        private void myCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        var dObj = sender as DependencyObject;
        if(dObj == null) return;
        var ob = dObj.GetChildOfType<ContentControl>();
        if (ob != null)
        {
            myCanvas.Children.Remove(ob);
        }
    }

辅助代码:

 public static T GetChildOfType<T>(this DependencyObject depObj)
    where T : DependencyObject
    {
        if (depObj == null) return null;
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            var child = VisualTreeHelper.GetChild(depObj, i);
            var result = (child as T) ?? GetChildOfType<T>(child);
            if (result != null) return result;
        }
        return null;
    }

只是把helper放在公共静态类中,因为它是一个扩展方法

您可以添加控件,例如:

Rectangle r = new Rectangle() { Name = "MyName" };

和从画布中删除:

UIElement element = StationLayout.FindName ("MyName") as UIElement;
StationLayout.Children.Remove(element);