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

时间:2012-05-23 09:40:42

标签: c# wpf winforms visual-studio-2010 user-controls

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

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

在我的xaml中,我有这一行:

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

然后我在我的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>

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

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

我尝试使用ZapTicketPrinter并且无法识别。

我也尝试了以下内容:

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

但得到一个空

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

2 个答案:

答案 0 :(得分:10)

提供x:名称而不是printer:name

<WindowsFormsHost>
    <Printers:TicketPrinter x:Name="ZapTicketPrinter"/>
</WindowsFormsHost>

MSDN示例

使用后面的代码 http://msdn.microsoft.com/en-us/library/ms751761.aspx
Walkthrough: Hosting a Windows Forms Control in WPF

使用xaml
http://msdn.microsoft.com/en-us/library/ms742875.aspx
Walkthrough: Hosting a Windows Forms Control in WPF by Using XAML

答案 1 :(得分:3)

尝试使用以下代码:

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);
}