我有一个WPF应用程序。在其中一个XAML中,我使用了Name属性,如下所示
x:Name="switchcontrol"我必须使用.cs文件访问this.switchcontrol文件中的控件/属性--我的问题是,我需要在静态方法中访问该控件,如
public static getControl()
{
var control = this.switchcontrol;//some thing like that
}如何做到这一点?
发布于 2013-12-10 09:59:16
在静态方法中无法访问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!!
}
}发布于 2013-12-10 10:12:56
有些替代Tony的方法-您可以传入窗口(或任何您正在使用的xaml构造)作为方法的引用。
public static void GetControl(MainWindow window)
{
var Control = window.switchcontrol;
}如果要传递几种不同派生类型的窗口,也可以这样做:
public static void GetControl(Window window)
{
dynamic SomeTypeOfWindow = window;
try
{
var Control = SomeTypeOfWindow.switchcontrol;
}
catch (RuntimeBinderException)
{
// Control Not Found
}
}https://stackoverflow.com/questions/20490770
复制相似问题