mwilson
mwilson

Reputation: 12990

Adding User Control (WPF) to Panel in Windows Form c#

I'm making an Outlook add in that when a user launches the add in, a windows form comes up. within this windows form, I will be dynamically adding user controls based on the user input.

The problem i'm having is adding the control programmatically. It all works fine if I just add a standard TextBox but when I add the user control, I get the below exception;

The best overloaded method match for 'System.Windows.Forms.Control.ControlCollection.Add(System.Windows.Forms.Control)' has some invalid arguments

cannot convert from 'OutlookAddIn.Controls.RForm' to 'System.Windows.Forms.Control'

I tried casting the control to an UserControl but a new exceptions arose.

Main Form:

using System.Windows.Forms;

namespace OutlookAddIn
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void lblReactiveMaintenance_Click(object sender, EventArgs e)
        {
            OutlookAddIn.Controls.RForm reactiveMaintForm = new OutlookAddIn.Controls.RForm();
            reactiveMaintForm.Name = "rForm";
            pnlMain.Controls.Add(reactiveMaintForm);
        }
    }
}

User Control:

namespace OutlookAddIn.Controls
{
    /// <summary>
    /// Interaction logic for RForm.xaml
    /// </summary>
    public partial class RForm : UserControl
    {
        public RForm()
        {
            InitializeComponent();
        }
    }
}

Upvotes: 1

Views: 2428

Answers (1)

Jeff
Jeff

Reputation: 1744

You should be able to use the ElementHost control to wrap the WPF control. See https://msdn.microsoft.com/en-us/library/system.windows.forms.integration.elementhost(v=vs.110).aspx.

private void lblReactiveMaintenance_Click(object sender, EventArgs e)
{
    OutlookAddIn.Controls.RForm = new OutlookAddIn.Controls.RForm();
    reactiveMaintForm.Name = "rForm";
    elementHost2.Child = reactiveMaintForm;
}

Upvotes: 3

Related Questions