C # using reflection to access Window Properties

How do you use reflection to access properties of Window objects?

Here's a minimal example:

.xaml file:

 <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow"> <TextBox x:Name="Textbox" Text=""/> </Window> 

code behind the file:

 public class A { public int Prop { get; set; } } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Test.Text = "blah"; PropertyInfo p1 = this.GetType().GetProperty("Textbox"); PropertyInfo p2 = new A().GetType().GetProperty("Prop"); } } 

p1 null ( p2 not as expected). Why is this so? Is the Window type a special object ? Or is it because the Textbox type is generated as an internal field?

  #line 5 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox Textbox; 
+5
source share
2 answers

As you can see, Textbox is a field, not a property. In addition, it is not publicly available, so you should try the following:

 FieldInfo f1 = this.GetType().GetField("Textbox", BindingFlags.NonPublic | BindingFlags.Instance); 
+2
source

All named elements become internal fields after compiling XAML. It:

 <TextBox x:Name="Textbox" Text=""/> 

eventually converted to this:

 internal TextBox TextBox; 

Therefore, to get the metadata, you must call GetField as follows:

 GetType().GetField("NameInXaml", BindingFlags.Instance | BindingFlags.NonPublic); 
+5
source

All Articles