Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access WPF Name properties in static method

Tags:

c#

wpf

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?

like image 376
Anees Deen Avatar asked Dec 10 '13 09:12

Anees Deen


People also ask

How can I find WPF controls by name?

FindName method of FrameworkElement class is used to find elements or controls by their Name properties. The FrameworkElement class is mother of all controls in WPF.

How can I access a control in WPF from another class or window?

If you want to access a control on a wpf form from another assembly you have to use the modifier attribute x:FieldModifier="public" or use the method proposed by Jean. Save this answer.

What is attached property WPF?

An attached property is a Extensible Application Markup Language (XAML) concept. Attached properties enable extra property/value pairs to be set on any XAML element that derives from DependencyObject, even though the element doesn't define those extra properties in its object model.

What are resources in WPF?

A resource is an object that can be reused in different places in your application. WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles.


1 Answers

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!!
    }

}
like image 56
Tony Avatar answered Sep 30 '22 18:09

Tony