繁体   English   中英

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

[英]WPF: Set MainWindow in App.xaml.cs, access it's variables

过去,我可以在关闭时访问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()窗口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'的第一个参数(是否缺少using指令或程序集引用?)

该框架将LoginWindow存储为Window

您可以将MainWindow强制转换LoginWindow

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

或使用as运算子

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

暂无
暂无

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

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