繁体   English   中英

WPF WindowsFormsHost Winform用户控件显示但不起作用

[英]WPF WindowsFormsHost Winform user control shows but does not function

我试图将现有的Winforms项目迁移到WPF。 但是:我需要离开一些用户控件作为WinForm控件。

我已将WinForms UserControl添加到WPF窗口中。 它由一个RichTextBox和一些按钮和标签组成。 这被细分为其他各种用户控件。

当我将UserControl嵌入WPF窗口时,它会呈现-但所有按钮似乎都无能为力。 当基础进程更新时,例如RichTextBox,它不显示内容。 但是,当我在调试中检查文本框时,我可以看到内容(尽管我必须单击“基本”才能看到此内容。)

[我发现的一个差异-尽管可能不相关-当该控件位于WPF上并且无法正常工作时,Visual Studio将对象显示为“密封”,但是当它在原始Winforms项目中时,它可以正常工作不显示为密封。 ]

我添加了代码来更改标签中的文本-并且它们也坚决拒绝更新:如果我以调试模式检查标签,则可以再次看到文本。

此堆栈溢出问题可能解决相同的问题: WindowsFormsHost Winform pdfviewer控件问题

但是答案对我来说没有多大意义:它提到了替换

new Window { Content = CreateContent(), Title = title }.Show();

但这不是我认识的一段代码:我正在使用一个xaml文件,其中包含后面的代码,并且使用

System.Windows.Application app = new System.Windows.Application(); 
app.Run(new FormWPFApp());

(其中,FormWPFApp是我在WPF窗口中的名称)

这是xaml标头:-

<Window x:Class="ZedApp.FormWPFApp"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Printers="clr-namespace:ZedApp.UserControls.Printers"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

        Title="Conversion version" Height="661" Width="1559" Loaded="Window_Loaded">

这是我用于两个UserControl的xaml(它们都继承自相同的基类):

<WindowsFormsHost Height="430" HorizontalAlignment="Left" Margin="192,32,0,0" Name="windowsFormsHostTicketPrinter" VerticalAlignment="Top" Width="324" Grid.Row="1" Grid.Column="1">
    <Printers:TicketPrinter x:Name="ticketPrinter">
    </Printers:TicketPrinter>
</WindowsFormsHost>
<WindowsFormsHost Height="430" HorizontalAlignment="Left" Margin="522,32,0,0" Name="windowsFormsHostJournalPrinter" VerticalAlignment="Top" Width="324" Grid.Row="1" Grid.Column="1">
    <Printers:JournalPrinter x:Name="journalPrinter">
    </Printers:JournalPrinter>
</WindowsFormsHost>

[[我注意到的另一件事是,如果在WPF中的WindowsFormsHost下运行,则清除其中一个窗口上的RTF文本框会开始踢出以下类型的错误的方法-“在窗口句柄不存在之前,无法在控件上调用Invoke或BeginInvoke被创建。”

private void ClearRichTextBox(RichTextBox rtbToClear)
{
    if (rtbToClear.IsHandleCreated)
    {

        if (rtbToClear.InvokeRequired)
        {
            this.Invoke(new Action<RichTextBox>(ClearRichTextBox), new object[] {rtbToClear});
            return;
        }

        rtbToClear.Clear();
    }
}

]

这种现象的可能原因是什么?为了使用户控件中的元素正常工作,我需要做什么?

与WinForms进行正确的输入互操作需要主机与WPF输入系统之间进行一些协作。 SDK中的Win32与WPF之间的消息循环主题很好地解释了这一点。 在您的设置中,最简单的方法是使用如下代码:

Window w = new Window1();
System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(w);
w.Show();

ElementHost.EnableModelessKeyboardInterop()本质上是向WinForms Application对象(通常运行消息循环)注册一个输入挂钩,并调用ComponentDispatcher.RaiseThreadMessage()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM