6

我正在将 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”时,它不能作为参考。

IE

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

我还尝试了以下方法:

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

但得到一个空

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

4

2 回答 2

11

提供 x:Name 而不是 printer:name

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

MSDN 示例


使用http://msdn.microsoft.com/en-us/library/ms751761.aspx演练背后的代码:在 WPF 中托管 Windows 窗体控件

使用 xaml
http://msdn.microsoft.com/en-us/library/ms742875.aspx
演练:使用 XAML 在 WPF 中托管 Windows 窗体控件

于 2012-05-23T09:43:29.697 回答
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);
}
于 2015-08-31T10:33:32.560 回答