0
votes

I want to have a return value from my WPF window without close it.

I have an DLL with WPF usercontrol inside, I call it from my DLL code. I have to call it, it returns me datas, then I send it datas. But I don't want to create two different instance of the same window.

My code :

        MP.UserControl1 a = new MP.UserControl1();
        a.ShowDialog();

        if (a.DialogResult.HasValue && a.DialogResult.Value == true)
        {
            a.Hide();
            InitialDatas = a.inputData;
        }
        else
            return 0;

Then I elaborate InitialDatas

And now I want to call a method inside my "a", and show it again, without create a new window.

Code :

        a.SetValue(result, off1, InitialDatas);
        a.ShowDialog();

I got error message : Cannot set visibility or call Show, ShowDialog or EnsureHandle after a window has been closed Is it possible to solve?

2
Do the dialog have to be Modal? Why not store the data/result in a ViewModel and simply create a new instance of the dialog and point it to the same ViewModel instance? - Emond Erno

2 Answers

3
votes

As the error message states, you cannot close the window and then open it again.

Instead of closing a window you could hide it by calling the Hide() method and then showing it again by calling the Show() method.

But since the ShowDialog() method doesn't return until the window has been closed, this won't work for a dialog window though. If you require a modal window, you will have to create a new instance of the window and open this one. This shouldn't really be an issue though.

So I guess the answer to your question is simply no. You cannot re-open a closed dialog window.

2
votes

I would solve this with an event model. You could do the following:

  • Create an event in the Form
  • Create an event handler in the caller
  • Subscribe to the event and do your logic

The called form:

namespace MyApplication
{
    public delegate void MyEventHandler(object source, EventArgs e);

    public class MyForm : Form
    {
        public event MyEventHandler OnInitialData;

        private void btnOk_Click(object sender, EventArgs e)
        {
             OnInitialData?.Invoke(this, null);
        }
    }
}

In your other Form:

MP.UserControl1 a = new MP.UserControl1();
a.OnInitialData += UCA_OnInitialData;

private void UCA_OnInitialData(object sender, EventArgs e)
{
    MP.UserControl1 a = sender as MP.UserControl1;
    a.SetValue(result, off1, a.inputData);
}
a.ShowDialog();