Search code examples
c#tagsuielement

How to automatically put in the tag the name of the UIElement


I know that this might seems very strange but I have the need to automatically put in the tag the name of a graphic Element e.g.

var tbkMain = new TextBlock(){Foreground = ...,..., Tag = ??? } <----here I wish automatically Tag= "TbkMain"

var grdSmall = new TextBlock(){Foreground = ...,..., Tag = ??? } <----here I wish automatically Tag= "grdSmall"

also something done afterwards like

tbkMain.Tag = ???;

or (and even better):

foreach(var element in grdMain.Children)
      element.Tag = ???

Thanks

I have to admit I do not even know if that is possible or where to start from. Thanks


Solution

  • From `here you can see that nameof is what you need.

    Therefore for example:

    tbkMain.Tag = nameof(tbkMain);
    

    but that is not very useful for it takes little to write tbkMain.Tag = "tbkMain"

    As for the other chance in my book it is not possible for if you do:

    foreach (UIElement item in grdAll.Children)
                item.Tag = nameOf(item);<----error
                    
    

    that is not possible for you have to define the type. And even if you do:

    foreach (UIElement item in grdAll.Children)
                {
                    if (item is TextBlock) (item as TextBlock).Tag = nameof(item);
                    if (item is StackPanel) (item as StackPanel).Tag = nameof(item);
                    ...
                }
    

    the result will be item and not the real name. Therefore useless. Sorry... `