2013-12-10 33 views
3

我有一个WPF应用程序。在XAML之一,我已经使用名称属性类似如下在静态方法中访问WPF名称属性

x:Name="switchcontrol" 

我使用this.switchcontrol 我的问题是访问cs文件控制/属性,我需要访问控制的静态方法一样

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

如何做到这一点?

回答

4

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

} 
+0

哇。非常感谢。有用。只是为了好奇,使用这种方法有什么缺点吗? –

+0

@anees是的,有一个,如果你有多个实例,那么你将获得最后创建窗口的控制权。你需要清除实例值,看看我更新的答案。 – Tony

+0

但是,我只需要创建一个实例。那么我应该继续使用旧实例吗? –

0

一些替代托尼的方法 - 你可以通过在窗口(或任何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 
     } 
    }