首页 文章

如何在WPF应用程序中放置自定义Windows窗体控件?

提问于
浏览
5

作为一个短期解决方案,我试图将Windows窗体'usercontrol'阻塞到WPF应用程序中 . 我在WPF应用程序视图中看到我可以向项目添加“自定义窗体控件”,它会创建一个空的自定义控件,但我无法弄清楚如何添加它 . 理想情况下,我想知道如何从我编译的Windows窗体用户控件中获取.dll并将其粘贴到WPF应用程序中,或将用户控件导入WPF应用程序 .

谢谢,山姆

3 回答

  • 0

    您无法像在Windows窗体应用程序中那样将其作为控件添加到工具箱中 . 你应该做的是“托管”WPF应用程序内部的用户控件 .

    See how to do it on MSDN .

    以下是如何使用屏蔽文本框(您可以轻松修改以使用自定义控件)的示例:

    <Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"  
    Title="HostingWfInWpf">
    <Grid>
        <WindowsFormsHost>
           <wf:MaskedTextBox x:Name="mtbDate" Mask="00/00/0000"/>
        </WindowsFormsHost>
    </Grid>
    </Window>
    
  • 7

    将System.Windows.Forms和WindowsFormsIntegration的引用添加到项目中

    xmlns:WinForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    xmlns:WindowsFormsIntegration="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    

    并将Windows窗体主机放在窗口中 .

    <WindowsFormsHost Name="wfhDate"  
                        HorizontalAlignment="Center" 
                        VerticalAlignment="Stretch">
                    <WinForms:FlowLayoutPanel/>
      </WindowsFormsHost>
    

    现在用C#代码

    using Forms = System.Windows.Forms;
    .........................
    Forms.FlowLayoutPanel flpPanel = this.wfhDate.Child as Forms.FlowLayoutPanel;
    // Initialize your Forms contol here.
    flpPanel.Controls.Add( yourControl );
    
  • 3

    卢卡斯的回答是正确的,但我想补充一些必要的东西 . 如果要创建Web应用程序,则必须将“安全性”设置更改为“这是完全信任的应用程序” . 在执行此操作之前,我无法使WindowsFormsHost控件正常工作 .

相关问题