如何使用MainWindow C#WPF中的getter

时间:2018-01-03 19:57:16

标签: c# wpf xaml getter

我的问题是,我无法在其他类中使用我的getter,因为getter位于MainWindow.xaml.cs类中。

当我在我的其他类ControlKey.cs中使用此Code *时,我得到一个异常,即应用程序保持不变。我认为它想要创建另一个Window但我只想在类ControlKey.cs中使用getter

MainWindow.xaml.cs 类:

 public bool GetPresentationStarted(){
            return presentationsarted;
 }

*

ControlKey.cs 类:

MainWindow mWindow = new MainWindow();

bool presentationStarted;

后来我有一个if语句,如果presentationStarted为true,我会做一些事情。 ...

presentationStarted = mWindow.GetPresentationStarted();

...

if (presentationStarted == true) {
...
}

我不知道如何做到与众不同。我希望有人可以帮助我

2 个答案:

答案 0 :(得分:2)

MainWindow的每个实例都有自己的presentationsarted副本。如果您希望从应用程序的主窗口中获取presentationsarted的值,则不能只创建MainWindow的新实例。该新实例与已经显示的其他实例无关。

但是你可以获得实际的主窗口。

var mWindow = (MainWindow)App.Current.MainWindow;

var x = mWindow.GetPresentationStarted();

这样可行,但这不是编写WPF应用程序的最佳方式。您应该学习MVVM(“Model-View-ViewModel”)模式。然后每个窗口都有自己的viewmodel,它拥有类似于那个的属性,并且所有的viewmodel都可以共享一个对每个人都关心的状态的常见viewmodel的引用。具有MVVM模式的WPF非常强大。然而,学习曲线很粗糙。

答案 1 :(得分:0)

因为您不需要MainWindow类中的任何其他参数,所以只需尝试使用: 1.静态属性。例如,您可以创建

public static bool? MainWindow.PresentationStarted {get; private set;} 

并设置您喜欢的任何事件的值。

或者

2.创建共享实例,如:

public static bool? SharedClass.MainPresentationStarted {get; set;}.

因此您可以访问该值:

if (MainWindow.PresentationStarted == true)