簡體   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