问题描述
我知道这可能看起来很奇怪,但我需要自动将图形元素的名称放入标签中 例如
var tbkMain = new TextBlock(){Foreground = ...,...,Tag = ??? } <----here I wish automatically Tag= "TbkMain"
var GrdSmall = new TextBlock(){Foreground = ...,Tag = ??? } <----here I wish automatically Tag= "GrdSmall"
之后也做了一些事情
tbkMain.Tag = ???;
或(甚至更好):
foreach(var element in GrdMain.Children)
element.Tag = ???
谢谢
我不得不承认我什至不知道这是否可能或从哪里开始。 谢谢
解决方法
从 `here 你可以看到 nameof 就是你所需要的。
因此例如:
tbkMain.Tag = nameof(tbkMain);
但这不是很有用,因为它几乎不需要编写 tbkMain.Tag = "tbkMain"
至于我书中的另一个机会,如果你这样做是不可能的:
foreach (UIElement item in grdAll.Children)
item.Tag = nameOf(item);<----error
这是不可能的,因为您必须定义类型。 即使你这样做:
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);
...
}
结果将是项目而不是真实姓名。所以没用。 对不起... `