简体   繁体   中英

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();
        }
    }
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM