c# - 无法通过 FieldInfo 从 xaml 模板访问字段

标签 c# wpf xaml reflection

我的 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/

相关文章:

c# - 大量客户端和大量数据的 WCF 怎么样?

c# - 使用 SSH.NET 流式传输私钥的问题

c# - LiveCharts上的自定义类(class)?

.net - 有没有办法确定当前屏幕是否支持触摸?

wpf - InvokeCommandAction 未调用

c# - Visual Studio 2013 的 XAML 错误

c# - 在后面的代码中反序列化 JSON 字符串

c# - 异步等待 vs GetAwaiter().GetResult() 和回调

c# - 如何为我的 bool 属性正确实现 INotifyPropertyChanged 并绑定(bind)到 CheckBox.IsChecked?

c# - 如何使用 Databound Itemscontrol 自定义 DataGrid 的 header