Adding and Removing UIElements WPF at Run Time

Is there a way to logically group or tag UIElements, such as forms and controls, added at runtime for easy deletion?

For example, I have a Grid with some (project) children and add Ellipses and TextBlock to it at runtime. When I want to draw a different set of ellipses and TextBlock s, I would like to delete the original set that I added. What would be an easy way to group them logically when adding them, so that I can just have child.clear () or somehow identify them to remove them?

You can add a tag value, but there is no way to get or read it when repeating through the children of a control, because they are of type UIElement , which does not have a tag property.

Thoughts?

+4
source share
2 answers

A very good place to use the 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)); } 

Using:

 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); } } 
+10
source

Try drawing a Canvas inside your grid ... as easy as:

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

Hope this helps.

+3
source

Source: https://habr.com/ru/post/1332621/


All Articles