我的 MainWindow 类有 xaml 模板:
...
<Button x:Name="button1" Content="Button" Click="button1_Click" />
<Label x:Name="superLabel" Content="Super content!" />
...
我想在单击按钮后通过反射访问superLabel字段,如下所示:
public void button1_Click(object sender, RoutedEventArgs e)
{
Type t = typeof(MainWindow);
FieldInfo test1 = t.GetField("superLabel"); // test1 == null
FieldInfo test2 = t.GetRuntimeField("superLabel"); // test2 == null
...
}
但我在每次测试中都得到null...
最佳答案
您的标签不是public
- 您应该添加BindingFlags
作为第二个参数:
FieldInfo test1 = t.GetField("superLabel", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
关于c# - 无法通过 FieldInfo 从 xaml 模板访问字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42318684/