wpf 从另一个类访问 mainwindow.xaml.cs 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12542576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing mainwindow.xaml.cs methods from another class
提问by ahmad05
hi i am relatively new at Wpf application
嗨,我是 Wpf 应用程序的新手
i want to know that can i create a object of mainwindow.xaml.csin some other class
And then using that object excess the user defined methods in mainwindow.xaml.cs
我想知道我可以mainwindow.xaml.cs在其他类中创建一个对象
然后使用该对象超出用户定义的方法mainwindow.xaml.cs
i am trying to something like this it creates the object of mainwindow but can't access the method the method which i am trying to access is public defined
我正在尝试这样的事情,它创建了 mainwindow 的对象,但无法访问该方法我试图访问的方法是公共定义的
MainWindow window = new Mainwindow();
window.point_to_screen();
it gives this error
它给出了这个错误
Error 2 The type name 'point_to_screen' does not exist in the type 'System.Windows.Window'
错误 2 类型名称“point_to_screen”在类型“System.Windows.Window”中不存在
回答by Ria
Make sure your method be in publicprotection level, and check if you use an instance method (not static) :
确保您的方法处于public保护级别,并检查您是否使用实例方法(不是static):
public class MainWindow
{
...
public void point_to_screen()
{
...
}
}
and use it:
并使用它:
MainWindow window = new Mainwindow();
window.point_to_screen();
if you use a staticmethod your code should be like this:
如果你使用一种static方法,你的代码应该是这样的:
public class MainWindow
{
...
public static void point_to_screen()
{
...
}
}
and use it:
并使用它:
MainWindow.point_to_screen();
回答by Youri Leenman
You should cast the current mainwindow to a MainWindow object. If you create a new window you won't be able to acces your current open window
您应该将当前主窗口转换为 MainWindow 对象。如果您创建一个新窗口,您将无法访问当前打开的窗口
MainWindow wnd = (MainWindow)Application.Current.MainWindow;
wnd.point_to_screen();

