问题描述
在 WPF 中,您只能在窗口上调用 ShowDialog
一次.之后就大功告成了.
In WPF you get to call ShowDialog
on a window exactly once. After that it is done for.
对我来说似乎有点蹩脚,但这是规则.如果你再次调用 ShowDialog
你会得到这个异常:
Seems kind of lame to me, but those are the rules. If you call ShowDialog
again you get this exception:
在窗口关闭后无法设置可见性或调用 Show、ShowDialog 或 WindowInteropHelper.EnsureHandle
我想知道的是:我怎样才能使用 Window
(或 UserControl
真的)并检查它是否有 ShowDialog
调用(所以我知道在再次调用 ShowDialog
之前要new
一个不同的).
What I want to know is: How can I take a Window
(or UserControl
really) and check to see if it has had ShowDialog
called (so I know to new
up a different one before calling ShowDialog
again).
像这样:
public void ShowListOfClients()
{
// | This is the method I want to write
// V
RefreshViewIfNeeded(_myWindowOrUserControlThatShowsAList);
FillWindowWithBusinessData(_myWindowOrUserControlThatShowsAList);
_myWindowOrUserControlThatShowsAList.ShowDialog();
}
注意: 很明显,在上面的示例中,每次输入方法时只需创建一个新的 WindowOrUserControlThatShowsAList
会更容易.但是请多考虑这个问题而不是愚蠢的例子.
NOTE: Clearly in the above example it would be easier to just create a new WindowOrUserControlThatShowsAList
every time I enter the method. But please consider the question more that the dumbed down example.
推荐答案
这不是 ShowDialog() 独有的,Show() 也有.不,没有要检查的 IsDisposed 属性.IsLoaded 只是解决方案的一半,第一次调用也是错误的.
This isn't exclusive to ShowDialog(), Show() does it too. And no, there is no IsDisposed property to check. IsLoaded is only half a solution, it will be false for the 1st invocation as well.
第一种方法是创建一个可以重新显示的对话框:
First approach is to just make a dialog that can be re-shown:
public bool CloseAllowed { get; set; }
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
if (!CloseAllowed) {
this.Visibility = System.Windows.Visibility.Hidden;
e.Cancel = true;
}
}
接下来是明确跟踪对象引用的健康状况:
The next one is to explicitly keep track of the health of the object reference:
private Window1 win = new Window1(); // say
private void button1_Click(object sender, RoutedEventArgs e) {
if (win == null) {
win = new Window1();
win.Closing += delegate { win = null; };
}
win.ShowDialog();
}
这篇关于如何检测窗口已用完它的“ShowDialog"?称呼的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!