【问题标题】:How to put a custom windows forms control in a WPF application?如何在 WPF 应用程序中放置自定义窗体控件?
【发布时间】:2010-11-21 13:29:53
【问题描述】:

作为一个短期解决方案,我试图将 Windows 表单“用户控件”插入 WPF 应用程序。我在 WPF 应用程序视图中看到我可以向项目添加一个“自定义 Windows 窗体控件”,它会生成一个空的自定义控件,但我不知道如何添加它。理想情况下,我想知道如何从我编译的 Windows 窗体用户控件中获取 .dll 并将其粘贴到 WPF 应用程序中,或者将用户控件导入 WPF 应用程序中。

谢谢, 山姆

【问题讨论】:

    标签: c# wpf user-controls


    【解决方案1】:

    您不能像在 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>
    

    【讨论】:

    • 我也完全按照原样尝试了这段代码,得到了我上面提到的同样的错误。
    • 您是否在 References 文件夹中添加了对 System.Windows.Forms 程序集的引用?
    • 是的,将它们添加到引用文件夹中。我环顾四周,回到您链接的页面,然后发现上面的页面向您展示了如何使用 c# 而不是 XAML 添加 WF 控件。我试过了,它起作用了,所以无论出于什么原因,在做一个 WPF Web 应用程序时,我都无法通过 XAML 让它工作,但我可以通过 c#。 msdn.microsoft.com/en-us/library/ms751761.aspx
    • 将此人标记为答案,因为它使我找到了解决方案:msdn.microsoft.com/en-us/library/ms751761.aspx
    • 太棒了,这完全符合预期。我能够从我的 Windows 窗体用户控件中获取生成的 dll 文件并将其添加为参考,然后将其添加到 WindowsFormsHost。可爱的。
    【解决方案2】:

    在您的项目中添加对 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 );
    

    【讨论】:

    • @Lucas:我从上面完全复制了 XAML,它编译时没有错误,我还没有输入 C# 代码,因为我只是想确保 XAML 正常工作。我运行了该应用程序,但它因以下异常而崩溃: System.Windows.Markup.XamlParseException 未处理 消息:无法创建在程序集“WpfUploaderTwo,版本=1.0.0.0,文化=中性,PublicKeyToken=null”中定义的“Page1”实例。调用的目标已引发异常。标记文件“Page1.xaml”第 1 行位置 7 中的错误。
    • 如果我取出 WindowsFormsHost 位,它工作得很好。代码和错误链接:bit.ly/aGqfG
    • 啊,所以我正在制作“WPF Web 应用程序”而不是“WPF 应用程序”,不确定这是否有任何影响。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-04
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2017-10-17
      • 1970-01-01
      • 2017-10-19
      相关资源
      最近更新 更多