Anees Deen
Anees Deen

Reputation: 1403

Access WPF Name properties in static method

I have a WPF application. In one of the XAML I have used Name attribute like as follows

 x:Name="switchcontrol"

I have to access the control/property in .cs file using this.switchcontrol My question is, I need to access the control in static method like

public static getControl()
{
 var control = this.switchcontrol;//some thing like that
}

How to achieve this?

Upvotes: 6

Views: 4505

Answers (2)

Tony
Tony

Reputation: 7445

this is not accessible in static method. You can try save reference to your instance in static property, for example:

public class MyWindow : Window
{

    public static MyWindow Instance { get; private set;}

    public MyWindow() 
    {
        InitializeComponent();
        // save value
        Instance = this; 
    }

    public static getControl()
    {
        // use value
        if (Instance != null)
            var control = Instance.switchcontrol; 
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        Instance = null; // remove reference, so GC could collect it, but you need to be sure there is only one instance!!
    }

}

Upvotes: 10

Gareth
Gareth

Reputation: 2791

Some alternatives to Tony's method - you could pass in the window (or whatever xaml construct you are using) as a reference to the method, e.g.

    public static void GetControl(MainWindow window)
    {
        var Control = window.switchcontrol;
    }

if you are going to be passing several different derived types of Window, you could also do this:

    public static void GetControl(Window window)
    {
        dynamic SomeTypeOfWindow = window;
        try
        {
            var Control = SomeTypeOfWindow.switchcontrol;
        }
        catch (RuntimeBinderException)
        {
            // Control Not Found
        }
    }

Upvotes: 1

Related Questions