简体   繁体   中英

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 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 is null ( p2 isn't as expected). Why is it so? Is the Window type some kind of a special object ? Or is it because the type of Textbox is generated as an internal field?

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

All named elements become internal fields, after XAML is compiled. This:

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

ultimately transforms to this:

internal TextBox TextBox;

Hence, to obtain metadata you have to call GetField this way:

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

As you found out yourself, Textbox is a field, not a property. In addition, it is not public, so you should try the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM