开发者

Instantiate a Windows Forms control in WPF without default constructor

开发者 https://www.devze.com 2022-12-14 17:03 出处:网络
I am trying to host a custom Windows Forms control in WPF. My custom control does not have a public constructor, and it has a static Create() method which looks something like this:

I am trying to host a custom Windows Forms control in WPF. My custom control does not have a public constructor, and it has a static Create() method which looks something like this:

public abstract class MyCustomControl : UserControl
{
  internal MyCustomControl(...) {  }

  public static MyCustomControl Create(SomeEnum kind)
  {
    switch (kind)
    {
      case SomeEnum.Kind1:
        return new MySuperCustomControl(...);
      ...
    }

What I want to do is instantiate this custom control in WPF and then have it hosted in WindowsFormsHost, but I obviously can't add an abstract class:

 <wfi:WindowsFormsHost Width="250" Height="150">
  <my:MyCust开发者_如何学JAVAomControl x:Name="customControl" />  <-- doesn't work
</wfi:WindowsFormsHost>

Is there a way I could add it into the "Host" via code?


You can't host control without public constructor in XAML. You can try two way:

  1. define name for your WindowsFormsHost and set Child property of WindowsFormsHost to your instance from static Create() in C# code. for example in initialize (or load) method. - it is simple way.
  2. try to bind Child property of WindowsFormsHost to Create() method. Frankly, I don't know or this approach will be work... but you can try :).. how bind to method in XAML? you can read - this or try to look in msdn or google :)


Found it, it's the WindowsFormsHost.Child property.

0

精彩评论

暂无评论...
验证码 换一张
取 消