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