jeudi 6 août 2015

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://ift.tt/o66D3f"
        xmlns:x="http://ift.tt/mPTqtT"
        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;





Aucun commentaire:

Enregistrer un commentaire