如何使用 MainWindow C# WPF 中的 getter
How to use the getter from MainWindow C# WPF
我的问题是,我无法在另一个 class 中使用我的 getter,因为 getter 在 MainWindow.xaml.cs class 中。
当我在我的其他 class ControlKey.cs 中使用此代码* 时,我得到一个异常,表明该应用程序处于暂停状态。我认为它想要创建另一个 Window 但我只想在 class ControlKey.cs
中使用 getter
MainWindow.xaml.cs Class:
public bool GetPresentationStarted(){
return presentationsarted;
}
*
ControlKey.cs Class:
MainWindow mWindow = new MainWindow();
bool presentationStarted;
后来我有一个 if 语句,如果 presentationStarted 为真,我会在其中执行某些操作。
...
presentationStarted = mWindow.GetPresentationStarted();
...
if (presentationStarted == true) {
...
}
我不知道怎么做不同。我希望有人能帮助我
MainWindow 的每个实例都有自己的 presentationsarted
副本。如果您想从应用程序的主 window 中获取 presentationsarted
的值,则不能只创建 MainWindow 的新实例。该新实例与已经显示的另一个实例无关。
但是您可以获得实际的主要 window 本身。
var mWindow = (MainWindow)App.Current.MainWindow;
var x = mWindow.GetPresentationStarted();
这可行,但这不是编写 WPF 应用程序的最佳方式。您真的应该学习 MVVM ("Model-View-ViewModel") 模式。然后每个 window 都会有自己的视图模型,拥有类似的属性,并且所有视图模型都可以共享对某些公共视图模型的引用,这些视图模型具有每个人都关心的状态。具有 MVVM 模式的 WPF 非常强大。然而,学习曲线是粗糙的。
因为您不需要 MainWindow 的任何其他参数 class 只需尝试使用:
1.静态属性。例如,您可以创建
public static bool? MainWindow.PresentationStarted {get; private set;}
并根据您喜欢的任何事件设置值。
或
2.Create 共享实例如:
public static bool? SharedClass.MainPresentationStarted {get; set;}.
因此您可以访问以下值:
if (MainWindow.PresentationStarted == true)
我的问题是,我无法在另一个 class 中使用我的 getter,因为 getter 在 MainWindow.xaml.cs class 中。
当我在我的其他 class ControlKey.cs 中使用此代码* 时,我得到一个异常,表明该应用程序处于暂停状态。我认为它想要创建另一个 Window 但我只想在 class ControlKey.cs
中使用 getterMainWindow.xaml.cs Class:
public bool GetPresentationStarted(){
return presentationsarted;
}
*
ControlKey.cs Class:
MainWindow mWindow = new MainWindow();
bool presentationStarted;
后来我有一个 if 语句,如果 presentationStarted 为真,我会在其中执行某些操作。 ...
presentationStarted = mWindow.GetPresentationStarted();
...
if (presentationStarted == true) {
...
}
我不知道怎么做不同。我希望有人能帮助我
MainWindow 的每个实例都有自己的 presentationsarted
副本。如果您想从应用程序的主 window 中获取 presentationsarted
的值,则不能只创建 MainWindow 的新实例。该新实例与已经显示的另一个实例无关。
但是您可以获得实际的主要 window 本身。
var mWindow = (MainWindow)App.Current.MainWindow;
var x = mWindow.GetPresentationStarted();
这可行,但这不是编写 WPF 应用程序的最佳方式。您真的应该学习 MVVM ("Model-View-ViewModel") 模式。然后每个 window 都会有自己的视图模型,拥有类似的属性,并且所有视图模型都可以共享对某些公共视图模型的引用,这些视图模型具有每个人都关心的状态。具有 MVVM 模式的 WPF 非常强大。然而,学习曲线是粗糙的。
因为您不需要 MainWindow 的任何其他参数 class 只需尝试使用: 1.静态属性。例如,您可以创建
public static bool? MainWindow.PresentationStarted {get; private set;}
并根据您喜欢的任何事件设置值。
或
2.Create 共享实例如:
public static bool? SharedClass.MainPresentationStarted {get; set;}.
因此您可以访问以下值:
if (MainWindow.PresentationStarted == true)