简体   繁体   English

如何在WPF的类文件中访问App.xaml中声明的Window对象?

[英]How to Access Window Object declared in App.xaml in class file in WPF?

I have Window object in App.xaml.cs file which is public. 我在公共的App.xaml.cs文件中有Window对象。 Now, i want to access this window object in class file. 现在,我想在类文件中访问此窗口对象。 Is it possible? 可能吗?

In App.xaml.cs file: 在App.xaml.cs文件中:

public partial class App : Application
    {
         public MyWindow mainWindowObj;

        void App_Startup(object sender, StartupEventArgs e)
        {
            mainWindowObj = new MyWindow();
            mainWindowObj.Show();
        }
    }

In Some Classfile.cs i want to access the 'mainWindowobj'. 在某些Classfile.cs中,我想访问“ mainWindowobj”。 I have tried following in Classfile.cs but error: 我在Classfile.cs中尝试了以下操作,但出现错误:

((App)Application.Current).mainWindowObj.Title="Hello";

this above line is sample i want to access the variables,objects inside this forms. 上面这行是示例,我想访问此表单中的变量,对象。

Help Appreciated! 帮助赞赏!

Converting my comment to an answer. 将我的评论转换为答案。

Namespace being used for Application appears to be System.Windows.Forms.Application rather than System.Windows.Application 用于Application命名空间似乎是System.Windows.Forms.Application,而不是System.Windows.Application

fix : (be explicit if needed or get rid of the using System.Windows.Forms; which you probably have somewhere in that scope) 修复 :(如果需要,请明确显示,或者摆脱using System.Windows.Forms;您可能已经在该范围内找到它了)

var currentApp = System.Windows.Application.Current as App;
if (currentApp != null)
  currentApp.mainWindowObj.Title = "Hello";

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

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