C#WPF为所有控件设置Tag = name

时间:2015-11-13 14:22:38

标签: c# wpf tags

我有一个带有各种控件的项目,有些名字有些,有些没有。 我想循环所有控件并在出现时自动设置Tag = Name。 我见过这样的各种解决方案:

WPF: How do I loop through the all controls in a window?

这可行,但我无法设置:

foreach (Visual ctrl in MainGrid.GetChildren())
{
    ctrl.Tag = ctrl.Name;<------
}

对我来说,标签用于在按下不同按钮时识别事件es。 感谢名单 帕特里克

1 个答案:

答案 0 :(得分:4)

Tag属性仅存在于FrameworkElements

所以你需要做一个演员:

foreach (Visual ctrl in MainGrid.GetChildren())
{
    FrameworkElement fxElt = ctrl as FrameworkElement;
    if( fxElt != null)
        fxElt.Tag = fxElt.Name;
}

此致