[英]Creating a form from a WinForms Control hosted within WPF — Owner is not set
我有以下场景(我已将其剥离为示例应用程序):
WindowsFormsHost
form1.Show(this)
。 问题是:
.Owner
属性为null。
.Owner
属性的工作,这意味着我不能忽略这个问题。 当然,理想情况下,这里没有任何依赖性。 .Owner
属性设置正确。 我能理解为什么这里有问题,但我希望我的下一个问题的答案可能是'是'!
有什么方法可以通过在等式的WPF方面进行更改来实现这一点吗?
如果不这样做,可以在WinForms方面做任何事情吗? (这可能超出了我可以在那里实现一些变化的可能性......)
这是我的示例应用程序中的代码。 首先是WPF方面:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="700">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Name="btnAdd" Click="btnAdd_Click" Content="Add Winform"/>
<WindowsFormsHost Grid.Row="1" Name="host" ScrollViewer.CanContentScroll="False"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
private WindowsFormsHost host;
public MainWindow()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
UserControl1 uc1 = new UserControl1();
WindowsFormsHost.EnableWindowsFormsInterop();
this.host.Child = uc1;
}
}
而现在WinForms方面......
UserControl1只是一个用户控件,上面有一个按钮和一个标签。 这是代码:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Show(this);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.label1.Text = "this: " + this + Environment.NewLine + "parent: " + this.Parent + Environment.NewLine + "toplevelcontrol: " + this.TopLevelControl;
}
}
Form1只是一个空表单。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
MessageBox.Show(" this: " + this + " owner: " + this.Owner);
}
}
在WPF中托管时,消息框中显示的Owner
和标签中显示的TopLevelControl
为null
,但在另一个WinForms应用程序中托管时具有值。
我想这里的问题是.Owner
是Form
类型,WPF应用程序中没有这种类型的实例。 很难想象财产在这种情况下可能具有的有效价值。 因此,似乎我需要更改代码,以便访问Form1中的`.Owner'属性。
<Window
xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
>
<my:WindowsFormsHost Name="MapHost" ScrollViewer.CanContentScroll="False" SizeChanged="MapHost_SizeChanged" />
MapControl继承System.Windows.Forms.Control
MapHost.Child = MapControl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.