WPF:在App.xaml.cs中设置MainWindow,访问它的变量

时间:2014-12-01 00:27:28

标签: c# wpf

过去我可以在关闭时访问一个windows变量,就像返回参数一样。但目前有这个问题。请参阅以下代码:

public partial class App : Application
    {
        //Public list of users and form can access
        ObservableCollection<User> LoggedUsers = new ObservableCollection<User>();
        public ObservableCollection<User> Logged
        {
            get
            {
                return LoggedUsers;
            }
        }

        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            if (!AreSettingsSet())
            {
                this.MainWindow = new Views.LoginWindow();
                this.MainWindow.ShowDialog(); // Waits until closed.

                //If the login form was closed properly, handle the user
                if (MainWindow.DialogResult == true)
                {
                    //Add the user to the list of logged users
                    User returned = MainWindow.returnUser;
                    LoggedUsers.Add(returned);
                }

                // Recheck the settings now that the login screen has been closed.
                if (!AreSettingsSet())
                {
                    // Tell the user there is a problem and quit.
                    this.Shutdown();
                }
            }

            this.MainWindow = new Views.Main();
            this.MainWindow.Show();
        }

        private bool AreSettingsSet()
        {
            MessageBox.Show(Logged.Count().ToString());
            return false;
        }
    }

如果AreSettingsSet方法返回false(此时正在进行测试),此代码应打开登录窗口。这工作正常,我遇到了从Views.LoginWindow()窗口获取对象的问题,这里是代码:

//Give App access to user object outside of this form
        public User returnUser
        {
            get
            {
                return user;
            }
        }

        //Public user object, start empty
        User user = new User();

我哪里错了?如何从登录窗口获取LoggedUsers对象?目前我在下一行收到错误。

代码:

User returned = MainWindow.returnUser;

错误:

  

'System.Windows.Window'不包含'returnUser'的定义   没有扩展方法'returnUser'接受第一个参数   类型'System.Windows.Window'可以找到(你错过了使用   指令或程序集引用?)

1 个答案:

答案 0 :(得分:2)

框架将 LoginWindow 存储为窗口

您可以将 MainWindow 转换为 LoginWindow

User returned = ((Views.LoginWindow)MainWindow).returnUser;

或使用作为运算符

User returned = (MainWindow as Views.LoginWindow).returnUser;