WPF 提供了许多具有丰富功能集的控件。 但是,有时你可能想要在 WPF 页面上使用 Windows 窗体控件。 例如,你可能对现有 Windows 窗体控件进行了大量投资,或者你可能拥有提供独特功能的 Windows 窗体控件。
本演练演示如何使用代码在 WPF 页上托管 Windows 窗体 System.Windows.Forms.MaskedTextBox 控件。
有关本演练中显示的任务的完整代码列表,请参阅 在 WPF 示例中托管 Windows 窗体控件。
先决条件
需要 Visual Studio 才能完成本演练。
托管 Windows Forms 控件
承载 MaskedTextBox 控件
创建名为
HostingWfInWpf
的 WPF 应用程序项目。添加对以下程序集的引用。
WindowsFormsIntegration
System.Windows.Forms
在 WPF 设计器中打开 MainWindow.xaml。
将 Grid 元素
grid1
命名为 .<Grid Name="grid1"> </Grid>
在“设计”视图或 XAML 视图中,选择该 Window 元素。
在“属性”窗口中,单击“ 事件 ”选项卡。
双击 Loaded 事件。
插入以下代码来处理 Loaded 事件。
private void Window_Loaded(object sender, RoutedEventArgs e) { // Create the interop host control. System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost(); // Create the MaskedTextBox control. MaskedTextBox mtbDate = new MaskedTextBox("00/00/0000"); // Assign the MaskedTextBox control as the host control's child. host.Child = mtbDate; // Add the interop host control to the Grid // control's collection of child controls. this.grid1.Children.Add(host); }
Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs) ' Create the interop host control. Dim host As New System.Windows.Forms.Integration.WindowsFormsHost() ' Create the MaskedTextBox control. Dim mtbDate As New MaskedTextBox("00/00/0000") ' Assign the MaskedTextBox control as the host control's child. host.Child = mtbDate ' Add the interop host control to the Grid ' control's collection of child controls. Me.grid1.Children.Add(host) End Sub
在文件的顶部,添加以下
Imports
或using
语句。using System.Windows.Forms;
Imports System.Windows.Forms
按 F5 生成和运行应用程序。