C# 如何将 WinForm 用户控件添加到 WPF 中,以便我可以在 xaml.cs 文件中引用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10717305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:57:42  来源:igfitidea点击:

How to add WinForm User Control Into WPF so that I can reference it in the xaml.cs file

c#wpfwinformsvisual-studio-2010user-controls

提问by Paul H

I am migrating part of a WinForms project into WPF.

我正在将 WinForms 项目的一部分迁移到 WPF。

I want to add an existing WinForms User Control into a WPF Form. The WinForm user control is called "TicketPrinter" and lives in the same project as the WPF form.

我想将现有的 WinForms 用户控件添加到 WPF 表单中。WinForm 用户控件称为“TicketPrinter”,与 WPF 表单位于同一项目中。

In my xaml I have this line:

在我的 xaml 中有这一行:

xmlns:Printers="clr-namespace:Project.UserControls.Printers"

And then I use it in my xaml here:

然后我在我的 xaml 中使用它:

        <WindowsFormsHost Height="430" HorizontalAlignment="Left" Margin="468,12,0,0" Name="windowsFormsHost1" VerticalAlignment="Top" Width="324">
            <Printers:TicketPrinter Printers:Name="ZapTicketPrinter">
            </Printers:TicketPrinter>
        </WindowsFormsHost> 
    </Grid>
</Window>

When I run the project the user control appears on the form as expected.

当我运行项目时,用户控件按预期出现在表单上。

But when I go into the code behind xaml.cs file and try to access "ZapTicketPrinter" it is not available as a reference.

但是当我进入 xaml.cs 文件后面的代码并尝试访问“ZapTicketPrinter”时,它不能作为参考。

i.e.

IE

I try using ZapTicketPrinter and it's not recognised.

我尝试使用 ZapTicketPrinter,但无法识别。

I've also tried the following:

我还尝试了以下方法:

TicketPrinter ticketPrinter = this.FindName("ZapTicketPrinter") as TicketPrinter;

but get a null

但得到一个空值

What am I missing? How do I reference the name in my code?

我错过了什么?如何在我的代码中引用名称?

回答by Hanzla Mateen

Try using following code:

尝试使用以下代码:

private void LoadWFUserControl() 
{
    // Initialize a Host Control which allows hosting a windows form control on WPF. Ensure that the WindowsFormIntegration Reference is present.
    System.Windows.Forms.Integration.WindowsFormsHost host =
        new System.Windows.Forms.Integration.WindowsFormsHost();

    // Create an object of your User control.
    MyWebcam uc_webcam = new MyWebcam();

    // Assign MyWebcam control as the host control's child.
    host.Child = uc_webcam;

    // Add the interop host control to the Grid control's collection of child controls. Make sure to rename grid1 to appr
    this.grid1.Children.Add(host);
}