How to automatically set Tag=name in code behind

45 Views Asked by At

Is there any way to automatically achieve this for each UI element?

var UI = new UI(){ Name="MyUI", Tag=??? }

for example with a button it might be

var btn = new Button(){ Name="myButton", Tag=???  }

Of course I might do it manually but for any element it gets boring and error prone. That would help me when I have to search for it on the UI Tree

Thanks

2

There are 2 best solutions below

0
Patrick On BEST ANSWER

First thing first let me state that the idea is of David Venegoni for Winform. Instead if you want to have it in WPF you can do this:

public static void GetChildrenList(Visual parent, List<Visual> collection)
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        // Get the child visual at specified index value.
        Visual childVisual = (Visual)VisualTreeHelper.GetChild(parent, i);

        // Add the child visual object to the collection.
        collection.Add(childVisual);

        // Recursively enumerate children of the child visual object.
        GetChildrenList(childVisual, collection);
    }
}

I just changed the name of the s/r but it is taken from here from dodgy coder.

And then you simply loop on the collection and do whatever you want:

foreach (var item in collection)
{
    if(item is Button)
    {
        (item as Button).Content = (item as Button).Name.Substring(3);
        (item as Button).Tag = (item as Button).Name;
    }
}

Ah very important remember do launch this after the element has been loaded otherwise you will get no children!

1
David Venegoni On

Not sure if this is a WinForms application or something else, but if it is a WinForms application, you can just recursively get all the child controls of form and set the Tag to the Control's Name. This should be done after the InitializeComponent call (to ensure all controls have been created and initialized) which is usually part of the constructor.

Here is some example code:

Recursively Get All Child Controls

    protected static IList<T> GetChildren<T>(Control control)
        where T : Control
    {
        if (control?.Controls== null)
            return new List<T>();

        var childControls = control.Controls.OfType<T>();
        return childControls.SelectMany(GetChildren<T>).Concat(childControls).ToList();
    }

Setting Control's Tag Value To Its Name

    public UI()
    {
        InitializeComponent();
        var controls = GetChildren<Control>(this);
        foreach (var control in controls)
            control.Tag = control.Name; 
    }

This is just one potential approach.