none
Can't host WPF control in WinForms RRS feed

  • Question

  • Hi
    I have problem with hosting WPF controls inside of Windows Form.
    I wrote WPF control and when I want to drag and drop this control onto WinForm I got this message

    [URL=http://img256.imageshack.us/i/clipboard01qpg.jpg/][IMG]http://img256.imageshack.us/img256/629/clipboard01qpg.th.jpg[/IMG][/URL]

    So I tried to add ElementHost to form and add my control to child collection. Then I got this error

    [URL=http://img146.imageshack.us/i/clipboard03ae.jpg/][IMG]http://img146.imageshack.us/img146/4023/clipboard03ae.th.jpg[/IMG][/URL]

    The constructor of my control looks like this

     public UserControl1()
        {
          
          InitializeComponent();
        }
    

    However if I add WPF control into elementHost in a runtime like this (the cod was added into form constructor)

     ucWPFControl = new UserControl1();
          ucWPFControl.Width = elementHost.Width;
          ucWPFControl.Height = elementHost.Height;
          elementHost.Child = ucWPFControl;
    

    The control works fine.

    Whad do I do wrong ??

     

    Saturday, July 24, 2010 7:22 PM

Answers

  • Hi Nocturn,

    You need to add another control as the wrapper of the WPF UserControl. In windows forms project, we can only drag a windows forms control onto the form. You could follow the code snippet below:

      public class WPFControlWrapper : ElementHost
      {
        private UserControl1 ucWPFControl;
        public WPFControlWrapper()
        {
          ucWPFControl = new UserControl1();
          ucWPFControl.Width = this.Width;
          ucWPFControl.Height = this.Height;
          this.Child = ucWPFControl;
        }
      }
    

    Let me know if this does not help.
    Aland Li 


    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
    Friday, July 30, 2010 11:56 AM
    Moderator