2017-02-18 36 views
1

提起我的XAML模板我的MainWindow類:無法訪問XAML的模板,通過字段信息

...  
<Button x:Name="button1" Content="Button" Click="button1_Click" /> 
<Label x:Name="superLabel" Content="Super content!" /> 
... 

我想通過訪問relfections 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 
    ... 
} 

但我在每次測試得到 ...

回答

1

你的標籤不是public - 你應該添加BindingFlags作爲第二個參數:

FieldInfo test1 = t.GetField("superLabel", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); 
+0

它的作品!謝謝@Roma –

+0

@DariuszFilipiak,不客氣 –