在运行时添加和移除WPF UI元素

5
有没有一种方法可以在运行时添加的形状和控件等UI元素逻辑地分组或标记以便于轻松删除?
例如,我有一个带有一些(设计时)子元素的Grid,并在运行时添加椭圆和TextBlock。当我想要绘制另一组椭圆和TextBlock时,我想要删除我添加的原始组。在添加它们时,有什么简单的方法可以将它们逻辑地分组,以便我只需使用children.clear()或某种方式来识别它们以删除它们?
可以添加标签值,但是在遍历控件的子元素时无法检索或读取此值,因为它们是UIElement类型,没有标签属性。
你有什么想法?
2个回答

11

使用附加属性(Attached Property)的一个非常好的场所。

示例:

// Create an attached property named `GroupID`
public static class UIElementExtensions
{
    public static Int32 GetGroupID(DependencyObject obj)
    {
        return (Int32)obj.GetValue(GroupIDProperty);
    }

    public static void SetGroupID(DependencyObject obj, Int32 value)
    {
        obj.SetValue(GroupIDProperty, value);
    }

    // Using a DependencyProperty as the backing store for GroupID.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty GroupIDProperty =
        DependencyProperty.RegisterAttached("GroupID", typeof(Int32), typeof(UIElementExtensions), new UIPropertyMetadata(null));
}

使用方法:

public void AddChild(UIElement element, Int32 groupID)
{
    UIElementExtensions.SetGroupID(element, groupID);
    rootPanel.Children.Add(element);
}

public void RemoveChildrenWithGroupID(Int32 groupID)
{
    var childrenToRemove = rootPanel.Children.OfType<UIElement>().
                           Where(c => UIElementExtensions.GetGroupID(c) == groupID);

    foreach (var child in childrenToRemove)
    {
        rootPanel.Children.Remove(child);
    }
}

这真的对我很有用,而且运行得很好。非常感谢。由于我的父元素是用户控件,所以我还没有能够使删除部分的查询工作,因此类型与面板不同,但这应该很简单。 - Ra.

3

尝试在网格中绘制Canvas...这样就像这样简单:

MyCanvas.Chlidren.Clear();
MyCanvas.Children.Add(new Ellipse { Canvas.Top = 3....});

希望这能有所帮助。

但是那里有设计时的子元素,我不想清除它们。 - Ra.
然后将那些您不想清除的内容放入一个数组中[使用x:Name],然后循环遍历画布子元素,清除不在数组中的任何内容。 - Machinarius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接