有没有办法逻辑分组或标记UIElements,如在运行时添加的形状和控件,以便于删除?
例如,我有Grid一些(设计时)子元素,并TextBlock在运行时添加省略号和s.当我想绘制一组不同的椭圆和TextBlocks时,我想删除我添加的原始集.什么是一个简单的方法来逻辑地组合这些添加它们,所以我可以有一个children.clear()或某种方式来识别它们以删除它们?
可以添加标记值,但是在迭代控件的子项时无法检索或读取它,因为它们的类型UIElement没有标记属性.
思考?
dec*_*one 10
一个非常好的地方使用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));
}
Run Code Online (Sandbox Code Playgroud)
用法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10037 次 |
| 最近记录: |