WPF には、豊富な機能セットを備えた多くのコントロールが用意されています。 ただし、WPF ページで Windows フォーム コントロールを使用したい場合があります。 たとえば、既存の Windows フォーム コントロールに多額の投資がある場合や、独自の機能を提供する Windows フォーム コントロールがある場合があります。
このチュートリアルでは、コードを使用して WPF ページで Windows フォーム System.Windows.Forms.MaskedTextBox コントロールをホストする方法について説明します。
このチュートリアルで示すタスクの完全なコード一覧については、「 WPF サンプルでの Windows フォーム コントロールのホスト」を参照してください。
[前提条件]
このチュートリアルを完了するには、Visual Studio が必要です。
Windows フォーム コントロールのホスト
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
押して、アプリケーションをビルドして実行します。
こちらも参照ください
.NET Desktop feedback