在 WPF 中实例化 Windows 窗体控件而不使用默认构造函数
我正在尝试在 WPF 中托管自定义 Windows 窗体控件。我的自定义控件没有公共构造函数,它有一个静态 Create()
方法,如下所示:
public abstract class MyCustomControl : UserControl
{
internal MyCustomControl(...) { }
public static MyCustomControl Create(SomeEnum kind)
{
switch (kind)
{
case SomeEnum.Kind1:
return new MySuperCustomControl(...);
...
}
我想要做的是在 WPF 中实例化此自定义控件,然后将其托管在WindowsFormsHost
,但我显然可以' t 添加抽象类:
<wfi:WindowsFormsHost Width="250" Height="150">
<my:MyCustomControl x:Name="customControl" /> <-- doesn't work
</wfi:WindowsFormsHost>
有没有办法通过代码将其添加到“主机”中?
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:MyCustomControl x:Name="customControl" /> <-- doesn't work
</wfi:WindowsFormsHost>
Is there a way I could add it into the "Host" via code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 XAML 中没有公共构造函数,则无法托管控件。
您可以尝试两种方法:
WindowsFormsHost 并设置 Child
WindowsFormsHost 的属性到您的
C# 中静态 Create() 的实例
代码。例如在初始化(或
负载)方法。 - 这是简单的方法。
坦白说,我不知道或者这个
方法会起作用......但你可以
尝试:)..如何绑定到 XAML 中的方法?
您可以阅读 - 此 或尝试
看看 msdn 或谷歌:)
You can't host control without public constructor in XAML.
You can try two way:
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.
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 :)
找到了,它是
WindowsFormsHost.Child
属性。Found it, it's the
WindowsFormsHost.Child
property.