0
votes

I have a wpf user control with a text box and a checkbox. The usercontrol is presented in a winforms Tab control using a element host. I would like the user control to pop out into a brand new winform by clicking a button on the user control.

I tried a sample project and I can simply do this by

void button1_Click(object sender, EventArgs e)
{
    Form frm = new Form();
    UserControl uc = userControl11;
    frm.Controls.Add(uc);
    frm.Show();
}

However, I would like a way so that the user can click a button to pop out the user control into a new form and then click the same button to close the new pop out form and show the control back in the tab page. Obviously, all the user entered data should still be present. Any thoughts?

2
why are you using WinForms TabControl? - paparazzo

2 Answers

0
votes

MVVM is your friend here. Concentrate all the logic (user data, popup state, etc) of your UserControl in a ViewModel object and set it to the control's DataContext. To "pop up" the control, just create a new one and set its DataContext to the ViewModel of the first. You can have a property in your ViewModel to know if the control is pop up or not, acting accordingly and toggling it when hitting the pop up button.

0
votes

Once you create your userControl it is created and you can assign it to another ElementHost( My example both forms have element Controls on them). See if this does what you want.

Form1

public partial class Form1 : Form
{
    Form2 frm2;
    bool popout = false;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (popout)
        {
            frm2.Close();
        }
        else
        {
            frm2 = new Form2();
            frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
            this.elementHost1.Child = null;
            frm2.setUserControl(userControl11);
            frm2.Show();
            popout = true;
        }
    }

    void frm2_FormClosed(object sender, FormClosedEventArgs e)
    {
        frm2.setUserControl(null);
        this.elementHost1.Child = userControl11;
        frm2.FormClosed -= new FormClosedEventHandler(frm2_FormClosed);
        popout = false;
    } 
}

Form2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
    public void setUserControl( System.Windows.Controls.UserControl item)
    {
        elementHost1.Child = item ;
    }
}