簡體   English   中英

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

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

我正在將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;

但得到一個空

我錯過了什么? 如何在代碼中引用該名稱?

提供x:名稱而不是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窗體控件

嘗試使用以下代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM