简体   繁体   English

如何从MainWindow C#WPF使用吸气剂

[英]How to use the getter from MainWindow C# WPF

My problem is, that I can't use my getter in my other class because the getter is in the MainWindow.xaml.cs class. 我的问题是,因为该吸气剂位于MainWindow.xaml.cs类中,所以无法在其他类中使用吸气剂。

When I use this Code* in my other class ControlKey.cs I get an exception that the Application is hold on. 当我在其他类ControlKey.cs中使用此Code *时,出现了应用程序被保留的异常。 I think it want's to create an other Window but I just want to use the getter in the class ControlKey.cs 我认为它想创建另一个Window,但我只想在ControlKey.cs类中使用getter

MainWindow.xaml.cs Class: MainWindow.xaml.cs类别:

 public bool GetPresentationStarted(){
            return presentationsarted;
 }

* *

ControlKey.cs Class: ControlKey.cs类别:

MainWindow mWindow = new MainWindow();

bool presentationStarted;

And later I have an if statement where I do something if presentationStarted is true. 然后,我有一个if语句,如果presentationStarted为true,该在哪里做某事。 ... ...

presentationStarted = mWindow.GetPresentationStarted();

... ...

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

I don't know how to do it different. 我不知道该怎么做。 I hope someone can help me 我希望有一个人可以帮助我

Each instance of MainWindow has its own copy of presentationsarted . MainWindow的每个实例都有其自己的presentationsarted副本。 If you want the value of presentationsarted from the main window of your application, you can't just create a new instance of MainWindow. 如果要在应用程序的主窗口中presentationsarted的值,则不能仅创建MainWindow的新实例。 That new instance has nothing to do with the other instance that's already showing. 该新实例与已经显示的另一个实例无关。

But you can get the actual main window itself. 但是您可以获取实际的主窗口本身。

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

var x = mWindow.GetPresentationStarted();

That'll work, but it's not the best way to write a WPF application. 那会起作用,但这不是编写WPF应用程序的最佳方法。 You should really learn the MVVM ("Model-View-ViewModel") pattern. 您应该真正学习MVVM(“模型-视图-视图模型”)模式。 Then each window would have its own viewmodel that owns properties like that one, and all the viewmodels can share a reference to some common viewmodel that has state everybody cares about. 然后,每个窗口将具有自己的视图模型,该视图模型具有与之类似的属性,并且所有视图模型都可以共享对某个公共视图模型的引用,该视图模型具有每个人都在乎的状态。 WPF with the MVVM pattern is immensely powerful. 带有MVVM模式的WPF非常强大。 The learning curve is rough, however. 但是,学习曲线很粗糙。

Because you don't require any other parameters from the MainWindow class just try to use: 1. Static property. 因为您不需要MainWindow类中的任何其他参数,所以请尝试使用:1.静态属性。 For example, you can create 例如,您可以创建

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

and set the value from any event you prefer. 并从您喜欢的任何事件中设置值。

Or 要么

2.Create shared instance like: 2.创建共享实例,例如:

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

So you have an access to the value: 因此,您可以访问该值:

if (MainWindow.PresentationStarted == true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM