【问题标题】:WPF Multiple dialogs, Visibility property issueWPF多个对话框,可见性属性问题
【发布时间】:2020-07-03 11:53:51
【问题描述】:

我有一个登录表单,它启动了一个讲师窗口的对话框

当交换窗口时,它看起来像这样:

//LoginWindow to LecturerClient
 this.Visibility = Visibility.Collapsed;
 LecturerWindow lecturerClient = new LecturerWindow(self);
 lecturerClient.Owner = this;
 lecturerClient.ShowDialog();
 this.Visibility = Visibility.Visible; // so when the lecturerClient dialogs exits - the login form will be visible

我的 LecturerWindow 还会打开另一个对话框:

//LecturerClient To Session
                Dispatcher.Invoke(() =>
                {
                    Visibility = Visibility.Collapsed;
                    Session newSession = new Session(mySelf, Courses.Find(item => item.courseId == courses[1].ToString()));
                    newSession.Owner = this;
                    newSession.ShowDialog();
                    Visibility = Visibility.Visible;
                });

当我的会话对话框关闭并且突然我的 LoginWindow 和我的 LecturerWindow 都变为可见时,问题就开始了,就像我的 LoginWindow 认为会话关闭是 LecturerWindow 关闭

提前谢谢你!

【问题讨论】:

  • 我无法准确解释这是为什么,但Dispatcher.Invoke 是导致问题的原因。我能够重现您的问题,并删除该行修复它。不过,不确定您将其用于什么目的,因此删除它可能不是一种选择。
  • 那么从线程控制 ui 元素的替代方法是什么?
  • 这取决于,您使用哪个类进行多线程处理? (即Task、BackroundManager等)

标签: c# wpf dialog window visibility


【解决方案1】:

我确定您已经解决了您的问题,但这里有一个供未来读者使用的解决方案:

我不会通过设置window.Visibility = Visibility.Collapsed; 来隐藏应用程序中的窗口,而是打开新窗口然后关闭旧窗口:

// in LoginWindow.xaml.cs
private void SubmitButton_OnClick(object sender, RoutedEventArgs e)
{
    // create a new window to show
    LecturerWindow newWindow = new LecturerWindow()
    {
        Title                 = "Lecturer Window",
        WindowStartupLocation = WindowStartupLocation.CenterScreen
    };
    // change the app main window to use the new window
    Application.Current.MainWindow = newWindow;
    newWindow.Show();
    // close the LoginWindow
    this.Close();
}

请注意,如果您在打开新窗口之前关闭了当前窗口,如果没有其他窗口打开,应用程序将启动关闭。此行为由Application.ShutdownMode 属性确定。通过在关闭当前窗口之前打开新窗口,我们可以避免这种情况(如上所示)。

同样可以在 LecturerClient 中打开会话窗口。

关闭LecturerClient 窗口时,您可以通过订阅Closing 事件再次打开一个新的LoginForm 窗口:

// in LecturerWindow.xaml.cs
public LecturerWindow()
{
    InitializeComponent();
    Closing += OnClosing;
}

// Open the login form again when this window is closing
private void OnClosing(object sender, CancelEventArgs e)
{
    // create a new window to show
    LoginWindow newMainWindow = new LoginWindow()
    {
        Title                 = "Login form window",
        WindowStartupLocation = WindowStartupLocation.CenterScreen
    };
    // change the app main window to use the new window
    Application.Current.MainWindow = newMainWindow;
    newMainWindow.Show();
    // This window is already closing, so we don't need to call Close()
}

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多