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

2023-09-07 15:08:59 作者:疏狂一醉

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

As a short term solution I'm trying to jam a windows form 'usercontrol' into a WPF application. I see in the WPF application view that I can add a 'custom windows form control' to the project and it makes an empty custom control, but I can't figure out how to add it. Ideally I'd like to know how to take the .dll from my compiled windows forms user control and stick it into the WPF app, or import the user control into the WPF application.

谢谢,山姆

推荐答案

您不能像在 Windows 窗体应用程序中那样将它作为控件添加到工具箱中.相反,您应该做的是在 WPF 应用程序中托管"用户控件.

You can't really add it as a control to the toolbox like you could for a Windows Forms Application. What you should do instead is "host" the user control inside of the WPF application.

在 MSDN 上查看操作方法.

这是一个如何使用蒙版文本框的示例(您可以轻松修改它以使用您的自定义控件):

Here's an example of how to use a masked text box (which you can easily modify to use your custom control):

<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>