c# - 设置对话框窗口的所有者时出现异常

标签 c# wpf dialog window

我有一个窗口,在我的应用程序中用作登录对话框。这是我的主窗口 View 模型中的按钮处理程序:

private void LoginDialogButtonPressed(object obj)
{
    var vm = new LoginDialogWindowVM(Controller);
    var window = new LoginDialogWindow(vm);
    window.Owner = Application.Current.MainWindow;
    window.ShowDialog();
}

我的登录窗口设置为 WindowStartupLocation="CenterOwner"。现在,这在 Debug模式下的 Visual Studio 中运行良好。但是在构建和运行版本时,打开登录对话框会引发异常:“无法将所有者属性设置为自身。”

如果我放下设置 window.Owner,该窗口只会在主监视器上的随机位置打开。

我在这里做错了什么?如何让登录窗口以 MainWindow 为中心打开而不抛出异常?

下面是抛出的整个异常:

enter image description here

最佳答案

你得到这个异常的原因是 LoginDialogWindow 在你的情况下是 Application.Current.MainWindowApplication.Current.MainWindow 不是t 返回 MainWindow 对象。

实现这一点的方法之一是

Window 作为 CommandParameter 从 View 传递到 ViewModel。

 <Button Content="OK" Command="{Binding OKCommand}"
         CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>

在ViewModel中,将与Owner相同的窗口设置为子窗口。

private void LoginDialogButtonPressed(object obj)
{
    var vm = new LoginDialogWindowVM(Controller);
    var window = new LoginDialogWindow(vm);
    window.Owner = obj as Window;
    window.ShowDialog();
}

这里参数object obj是View传过来的Window

关于c# - 设置对话框窗口的所有者时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51926870/

相关文章:

javascript - InDesign ScriptUI 窗口出现后立即消失

jQuery 对话框 - 在打开之前显示加载图像并加载内容

c# - 如何忽略以0开头的整数

c# - 在 Unity 中进行本地化的最佳方式

c# - 选择 TreeView 项而不调用 SelectedItemChanged?

当内容类型为 UserControl 时,WPF 为 ContentControl 编写 ControlTemplate

angular - 使用 Material 对话框在 Angular 元素上显示问题(ShadowDom 问题?)

c# - 使用反射初始化对象的自动属性——有什么注意事项吗?

c# - C#什么时候得到显式接口(interface)实现的?

c# - WPF 标签到文本框