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

时间:2013-06-27 07:50:59

标签: c# wpf xaml

我在App.xaml.cs文件中有Window对象是公共的。现在,我想在类文件中访问此窗口对象。有可能吗?

在App.xaml.cs文件中:

public partial class App : Application
    {
         public MyWindow mainWindowObj;

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

在一些Classfile.cs中我想访问'mainWindowobj'。我在Classfile.cs中尝试了以下但是错误:

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

以上这行是我想要访问变量的示例,这个表单中的对象。

帮助感谢!

1 个答案:

答案 0 :(得分:1)

将我的评论转换为答案。

用于Application的命名空间似乎是System.Windows.Forms.Application而不是System.Windows.Application

修复 :(如果需要,请明确或删除您可能在该范围内某处的using System.Windows.Forms;

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