5

有没有办法对 UIElement 进行逻辑分组或标记,例如在运行时添加的形状和控件以便于删除?

例如,我有Grid一些(设计时)子元素,并在运行时向它添加 Ellipses 和TextBlocks。当我想绘制一组不同的 Ellipses 和TextBlocks 时,我想删除我添加的原始集合。什么是在添加它们时对它们进行逻辑分组的简单方法,这样我就可以有一个 children.clear() 或某种方式来识别它们以删除它们?

可以添加标记值,但在遍历控件的子项时无法检索或读取此值,因为它们的类型UIElement没有标记属性。

想法?

4

2 回答 2

11

A very good place to use an Attached Property.

Example:

// 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));
}

Usage:

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);
    }
}
于 2010-12-18T19:11:42.500 回答
3

尝试在网格内部绘制Canvas...这样就很容易了:

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

希望能帮助到你。

于 2010-12-18T18:58:47.970 回答