如何使用MainWindow C#WPF中的getter

问题描述 投票:0回答:2

我的问题是,我不能在我的其他类中使用我的getter,因为getter在MainWindow.xaml.cs类中。

当我在我的其他类ControlKey.cs中使用此Code *时,我得到一个异常,即Application保持不变。我想它想要创建一个其他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) {
...
}

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

c# wpf xaml getter
2个回答
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非常强大。然而,学习曲线很粗糙。


0
投票

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

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

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

要么

2.创建共享实例,如:

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

因此您可以访问该值:

if (MainWindow.PresentationStarted == true)
© www.soinside.com 2019 - 2024. All rights reserved.