연습: WPF에서 Windows Forms 컨트롤 호스팅

WPF에서는 풍부한 기능 집합이 있는 많은 컨트롤을 제공합니다. 그러나 경우에 따라 WPF 페이지에서 Windows Forms 컨트롤을 사용해야 할 수 있습니다. 예를 들어 기존 Windows Forms 컨트롤에 상당한 투자를 했거나 고유한 기능을 제공하는 Windows Forms 컨트롤이 있을 수 있습니다.

이 연습에서는 코드를 사용하여 WPF 페이지에서 Windows Forms System.Windows.Forms.MaskedTextBox 컨트롤을 호스트하는 방법을 보여 줍니다.

이 연습에 설명된 작업의 전체 코드 목록은 WPF에서 Windows Forms 컨트롤 호스팅 샘플을 참조하세요.

필수 구성 요소

이 연습을 완료하려면 Visual Studio가 필요합니다.

Windows Forms 컨트롤 호스팅

MaskedTextBox 컨트롤을 호스트하려면

  1. HostingWfInWpf라는 WPF 애플리케이션 프로젝트를 만듭니다.

  2. 다음 어셈블리에 대한 참조를 추가합니다.

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. WPF Designer에서 MainWindow.xaml을 엽니다.

  4. Grid 요소의 이름을 grid1로 지정합니다.

    <Grid Name="grid1">
        
    </Grid>
    
  5. 디자인 뷰 또는 XAML 뷰에서 Window 요소를 선택합니다.

  6. 속성 창에서 이벤트 탭을 클릭합니다.

  7. Loaded 이벤트를 두 번 클릭합니다.

  8. 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
    
  9. 파일 맨 위에 다음 Imports 또는 using 문을 추가합니다.

    using System.Windows.Forms;
    
    Imports System.Windows.Forms
    
  10. F5 키를 눌러 애플리케이션을 빌드하고 실행합니다.

참고 항목