不久前我遇到了这个问题。我记得这是一个与顶级 WPF 消息循环有关的错误,它与 WinForms 消息循环不兼容。
我使用的解决方案是将最外层从 WPF 窗口更改为 WinForms 窗体。也就是说,我换了
new Window { Content = CreateContent(), Title = title }.Show();
与
new ElementHostForm(CreateContent(), title).Show();
通过使用这样的类:
class ElementHostForm : System.Windows.Forms.Form
{
ElementHost _host;
public WinFormsWindow(UIElement content, string title)
{
_host = new ElementHost { Child = content };
Controls.Add(host);
content.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if(content.DesiredSize.Width > 100 && content.DesiredSize.Height > 100)
ClientSize = _host.Size =
new Size((int)content.DesiredSize.Width, (int)content.DesiredSize.Height));
content.ClearValue(FrameworkElement.WidthProperty);
content.ClearValue(FrameworkElement.HeightProperty);
Title = title;
}
protected override void OnResize(EventArgs e)
{
if(!ClientSize.IsEmpty) _host.Size = ClientSize;
base.OnResize(e);
}
}
这通过允许 WinForms 拥有最外层的消息循环来解决该错误。
此更改对我来说非常容易,因为我已经在单独的 UserControl(而不是 Window)中拥有了我的顶级内容。如果您的顶级内容是 Window,您可能需要重构。