Search code examples
c#tagsuielementelementname

How to automatically set Tag=name in code behind


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


Solution

  • 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!