我有一个WPF应用程序.在其中一个XAML中我使用了Name属性,如下所示
x:Name="switchcontrol"
Run Code Online (Sandbox Code Playgroud)
我必须使用this.switchcontrol
我的问题访问.cs文件中的控件/属性,我需要以静态方法访问控件
public static getControl()
{
var control = this.switchcontrol;//some thing like that
}
Run Code Online (Sandbox Code Playgroud)
怎么做到这一点?
this静态方法无法访问.您可以尝试在静态属性中保存对实例的引用,例如:
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!!
}
}
Run Code Online (Sandbox Code Playgroud)