对于我的一生,我找不到解决方案:
我设置了一个类来执行几件事,其中之一是操作 wpf window 。这些窗口之一是 MainWindow.xaml
。
例如,我希望此类关闭 MainWindow.xaml
,也就是说,如果从 OtherClass.cs
中调用一个方法。
基本上:我想从远程类访问窗口 (MainWindow.xaml.cs
) 代码隐藏中未引用的方法,尽管在同一项目 (Visual Studio) 中。
当我使用 MainWindow (using MainWindow
或 imports MainWindow
in vb.net )并使用其成员关闭窗口时,如下所示:
using MainWindow
Public class OtherClass
{
// OtherClass is instanced elsewhere and then is decided to close MainWindow.
// So I imagine doing the following:
private void CommandClose()
{
CloseMainWindow();
}
...
}
在 MainWindow.xaml.cs 中:
Public class MainWindow
{
Public void CloseMainWindow()
{
this.close();
}
...
}
尽管我收到以下错误:“对非共享成员的引用需要对象引用”。
这意味着我应该做类似的事情:
using MainWindow
Public class OtherClass
{
MainWindow myWindow // Though now I have a new window :/
private void CommandClose()
{
myWindow.CloseMainWindow();
}
...
}
因此,要访问 MainWindow.xaml.cs 中的任何成员而不创建新实例,我需要共享它们吗?但这会违背让它对窗口执行任何操作的目的,因为那时关闭命令将不可用!
我可能忽略了一些事情,但 atm 我似乎没有注意到它。 有人可以告诉我处理这种情况的方法吗?
注意,如果有人想知道的话,我正在 Windows Presentation Foundation 工作。
为了进一步澄清,这里是对之前描述我的情况的答案之一的评论:
What I am trying to do is run a command within another class, which is a public member of a WPF window. The window is already instanced and displayed. I just want to access its public members so I can manipulate the window from another class for convenience sake. This OtherClass.cs of mine is a class that handles console actions. The console is a custom control situated in the MainWindow.xaml.cs. When the user types for instance: /close, I want the MainWindow.xaml to close, but not just that, for in the future I want to add more features.
最佳答案
您仍然需要一个对象引用。为此,您必须使用应用程序上下文。
以下是如何获取对已打开的任何类型窗口的引用列表并关闭它们的方法:
var windows = Application.Current.Windows.OfType<MainWindow>();
foreach (var window in windows)
{
window.Close();
}
您可以对它们调用您想要的任何其他方法,并且您可以搜索任何其他类型的窗口,但这就是您找到您专门寻找的窗口的方式。
关于c# - 如何从远程类调用未引用的方法? (允许 C# 和 VB.NET),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22516972/