DialogResult can be set only after Window is created and shown as dialog

故事扮演 提交于 2019-12-10 16:26:56

问题


I have a main WPF window, mywindow.showDialog when a button is clicked on the window, a command is executed let's say the command is SendToTableCommand

protected virtual void SendToTableExecute(object o)
{
    UIThread.BeginInvoke(new Action<object>(SendToTableExecuteUI),o);
}

private void SendToTableExecuteUI(object o)
{
    if (o is Control)
    {
        m_OwningWindow = UIHelper.FindVisualParent<Window>((Control)o);
    }

    do sth...

    if (m_OwningWindow != null)
    {
        //only set DialogResult when window is ShowDialog before
        if(System.Windows.Interop.ComponentDispatcher.IsThreadModal)
            m_OwningWindow.DialogResult = true;
    }
}

Sometime ago, m_OwningWindow.DialogResult = true throws exception. So I added an if check that uses IsThreadModal. It has worked for a while, but now m_OwningWindowdoes not close because IsThreadModal is false.

I do not know what's the right way to solve the issue and think I did not handle it properly. Please help. thanks in advance


回答1:


Jason's reply reminds me of a workaround. i.e. using Window.Close(), then add a bool type property on window, say OKClicked, replace anywhere that set DialogResult with window.Close(); window.OKClicked = true or false. replace reference to window.DialogResult with window.OKClicked. Any problem with the workaround? thanks




回答2:


I was hiding my window before assigning DialogResult. Swapping the order, so DialogResult is assigned before the window is hidden, fixed my problem. Even if the window was ShowDialog'd, it must be considered "open" in order for DialogResult to be set.

Edit: And the window should be closed, not hidden. That bit me after I posted.




回答3:


Use Form.Modal to determine if your form is being opened as a window or a modal dialog.

You should be able to Close() the form when you want it to close, regardless of whether it's a dialog or not. (Under certain circumstances you may also need to Dispose it after closing)

Also, DialogResult is an enumerated type - true isn't a value I'd expect to see being assigned to it. Typically DialogResult.OK or DialogResult.Yes would be used for this.



来源:https://stackoverflow.com/questions/5889162/dialogresult-can-be-set-only-after-window-is-created-and-shown-as-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!