Share via


연습: WindowsFormsHost 요소를 사용하여 속성 매핑

이 연습에서는 PropertyMap 속성을 사용하여 WPF 속성을 호스팅된 Windows Forms 컨트롤의 해당 속성에 매핑하는 방법을 보여 줍니다.

이 연습에서 설명하는 작업은 다음과 같습니다.

  • 프로젝트 만들기.

  • 애플리케이션 레이아웃 정의.

  • 새 속성 매핑 정의.

  • 기본 속성 매핑 제거.

  • 기본 속성 매핑 바꾸기.

  • 기본 속성 매핑 확장.

완료하면 WPF 속성을 호스팅된 Windows Forms 컨트롤의 해당 속성에 매핑할 수 있습니다.

필수 구성 요소

이 연습을 완료하려면 다음과 같은 구성 요소가 필요합니다.

  • Visual Studio 2017

프로젝트 만들기 및 설정

  1. PropertyMappingWithWfhSample이라는 WPF 앱 프로젝트를 만듭니다.

  2. 솔루션 탐색기에서 WindowsFormsIntegration.dll이라고 명명된 WindowsFormsIntegration 어셈블리에 대한 참조를 추가합니다.

  3. 솔루션 탐색기에서 System.Drawing 및 System.Windows.Forms 어셈블리에 대한 참조를 추가합니다.

애플리케이션 레이아웃 정의

WPF 기반 애플리케이션은 WindowsFormsHost 요소를 사용하여 Windows Forms 컨트롤을 호스트합니다.

애플리케이션 레이아웃을 정의하려면

  1. WPF 디자이너에서 Window1.xaml을 엽니다.

  2. 기존 코드를 다음 코드로 바꿉니다.

    <Window x:Class="PropertyMappingWithWfh.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PropertyMappingWithWfh" Height="300" Width="300"
        Loaded="WindowLoaded">
      <DockPanel Name="panel1" LastChildFill="True">
        <WindowsFormsHost Name="wfHost" DockPanel.Dock="Left" SizeChanged="Window1_SizeChanged" FontSize="20" />
      </DockPanel>
    </Window>
    
  3. 코드 편집기에서 Window1.xaml.cs를 엽니다.

  4. 파일의 맨 위에서 다음 네임스페이스를 가져옵니다.

    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Windows.Forms;
    using System.Windows.Forms.Integration;
    
    Imports System.Drawing
    Imports System.Drawing.Drawing2D
    Imports System.Windows.Forms
    Imports System.Windows.Forms.Integration
    

새 속성 매핑 정의

WindowsFormsHost 요소는 몇 가지 기본 속성 매핑을 제공합니다. WindowsFormsHost 요소의 PropertyMap에서 Add 메서드를 호출하여 새 속성 매핑을 추가합니다.

새 속성 매핑을 정의하려면

  • 다음 코드를 Window1 클래스의 정의에 복사합니다.

    // The AddClipMapping method adds a custom
    // mapping for the Clip property.
    private void AddClipMapping()
    {
        wfHost.PropertyMap.Add(
            "Clip",
            new PropertyTranslator(OnClipChange));
    }
    
    // The OnClipChange method assigns an elliptical clipping
    // region to the hosted control's Region property.
    private void OnClipChange(object h, String propertyName, object value)
    {
        WindowsFormsHost host = h as WindowsFormsHost;
        System.Windows.Forms.CheckBox cb = host.Child as System.Windows.Forms.CheckBox;
    
        if (cb != null)
        {
            cb.Region = this.CreateClipRegion();
        }
    }
    
    // The Window1_SizeChanged method handles the window's
    // SizeChanged event. It calls the OnClipChange method explicitly
    // to assign a new clipping region to the hosted control.
    private void Window1_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        this.OnClipChange(wfHost, "Clip", null);
    }
    
    // The CreateClipRegion method creates a Region from an
    // elliptical GraphicsPath.
    private Region CreateClipRegion()
    {
        GraphicsPath path = new GraphicsPath();
    
        path.StartFigure();
    
        path.AddEllipse(new System.Drawing.Rectangle(
            0,
            0,
            (int)wfHost.ActualWidth,
            (int)wfHost.ActualHeight ) );
    
        path.CloseFigure();
    
        return( new Region(path) );
    }
    
    ' The AddClipMapping method adds a custom mapping 
    ' for the Clip property.
    Private Sub AddClipMapping()
    
        wfHost.PropertyMap.Add( _
            "Clip", _
            New PropertyTranslator(AddressOf OnClipChange))
    
    End Sub
    
    ' The OnClipChange method assigns an elliptical clipping 
    ' region to the hosted control's Region property.
    Private Sub OnClipChange( _
    ByVal h As Object, _
    ByVal propertyName As String, _
    ByVal value As Object)
    
        Dim host As WindowsFormsHost = h
    
        Dim cb As System.Windows.Forms.CheckBox = host.Child
    
        If cb IsNot Nothing Then
            cb.Region = Me.CreateClipRegion()
        End If
    
    End Sub
    
    ' The Window1_SizeChanged method handles the window's 
    ' SizeChanged event. It calls the OnClipChange method explicitly 
    ' to assign a new clipping region to the hosted control.
    Private Sub Window1_SizeChanged( _
    ByVal sender As Object, _
    ByVal e As SizeChangedEventArgs)
    
        Me.OnClipChange(wfHost, "Clip", Nothing)
    
    End Sub
    
    ' The CreateClipRegion method creates a Region from an
    ' elliptical GraphicsPath.
    Private Function CreateClipRegion() As [Region] 
        Dim path As New GraphicsPath()
        
        path.StartFigure()
        
        path.AddEllipse(New System.Drawing.Rectangle( _
            0, _
            0, _
            wfHost.ActualWidth, _
            wfHost.ActualHeight))
        
        path.CloseFigure()
        
        Return New [Region](path)
    
    End Function
    

    AddClipMapping 메서드가 Clip 속성에 대한 새 매핑을 추가합니다.

    OnClipChange 메서드는 Clip 속성을 Windows FormsRegion 속성으로 변환합니다.

    Window1_SizeChanged 메서드는 창의 SizeChanged 이벤트를 처리하고 애플리케이션 창에 맞게 클리핑 영역의 크기를 지정합니다.

기본 속성 매핑 제거

WindowsFormsHost 요소의 PropertyMap에서 Remove 메서드를 호출하여 기본 속성 매핑을 제거합니다.

기본 속성 매핑을 제거하려면

  • 다음 코드를 Window1 클래스의 정의에 복사합니다.

    // The RemoveCursorMapping method deletes the default
    // mapping for the Cursor property.
    private void RemoveCursorMapping()
    {
        wfHost.PropertyMap.Remove("Cursor");
    }
    
    ' The RemoveCursorMapping method deletes the default
    ' mapping for the Cursor property.
    Private Sub RemoveCursorMapping()
        wfHost.PropertyMap.Remove("Cursor")
    End Sub
    

    RemoveCursorMapping 메서드는 Cursor 속성에 대한 기본 매핑을 삭제합니다.

기본 속성 매핑 바꾸기

기본 매핑을 제거하고 WindowsFormsHost 요소의 PropertyMap에서 Add 메서드를 호출하여 기본 속성 매핑을 대체합니다.

기본 속성 매핑을 바꾸려면

  • 다음 코드를 Window1 클래스의 정의에 복사합니다.

    // The ReplaceFlowDirectionMapping method replaces the
    // default mapping for the FlowDirection property.
    private void ReplaceFlowDirectionMapping()
    {
        wfHost.PropertyMap.Remove("FlowDirection");
    
        wfHost.PropertyMap.Add(
            "FlowDirection",
            new PropertyTranslator(OnFlowDirectionChange));
    }
    
    // The OnFlowDirectionChange method translates a
    // Windows Presentation Foundation FlowDirection value
    // to a Windows Forms RightToLeft value and assigns
    // the result to the hosted control's RightToLeft property.
    private void OnFlowDirectionChange(object h, String propertyName, object value)
    {
        WindowsFormsHost host = h as WindowsFormsHost;
        System.Windows.FlowDirection fd = (System.Windows.FlowDirection)value;
        System.Windows.Forms.CheckBox cb = host.Child as System.Windows.Forms.CheckBox;
    
        cb.RightToLeft = (fd == System.Windows.FlowDirection.RightToLeft ) ?
            RightToLeft.Yes : RightToLeft.No;
    }
    
    // The cb_CheckedChanged method handles the hosted control's
    // CheckedChanged event. If the Checked property is true,
    // the flow direction is set to RightToLeft, otherwise it is
    // set to LeftToRight.
    private void cb_CheckedChanged(object sender, EventArgs e)
    {
        System.Windows.Forms.CheckBox cb = sender as System.Windows.Forms.CheckBox;
    
        wfHost.FlowDirection = ( cb.CheckState == CheckState.Checked ) ?
                System.Windows.FlowDirection.RightToLeft :
                System.Windows.FlowDirection.LeftToRight;
    }
    
    ' The ReplaceFlowDirectionMapping method replaces the
    ' default mapping for the FlowDirection property.
    Private Sub ReplaceFlowDirectionMapping()
    
        wfHost.PropertyMap.Remove("FlowDirection")
    
        wfHost.PropertyMap.Add( _
            "FlowDirection", _
            New PropertyTranslator(AddressOf OnFlowDirectionChange))
    End Sub
    
    
    ' The OnFlowDirectionChange method translates a 
    ' Windows Presentation Foundation FlowDirection value 
    ' to a Windows Forms RightToLeft value and assigns
    ' the result to the hosted control's RightToLeft property.
    Private Sub OnFlowDirectionChange( _
    ByVal h As Object, _
    ByVal propertyName As String, _
    ByVal value As Object)
    
        Dim host As WindowsFormsHost = h
    
        Dim fd As System.Windows.FlowDirection = _
            CType(value, System.Windows.FlowDirection)
    
        Dim cb As System.Windows.Forms.CheckBox = host.Child
    
        cb.RightToLeft = IIf(fd = System.Windows.FlowDirection.RightToLeft, _
            RightToLeft.Yes, _
            RightToLeft.No)
    
    End Sub
    
    
    ' The cb_CheckedChanged method handles the hosted control's
    ' CheckedChanged event. If the Checked property is true,
    ' the flow direction is set to RightToLeft, otherwise it is
    ' set to LeftToRight.
    Private Sub cb_CheckedChanged( _
    ByVal sender As Object, _
    ByVal e As EventArgs)
    
        Dim cb As System.Windows.Forms.CheckBox = sender
    
        wfHost.FlowDirection = IIf(cb.CheckState = CheckState.Checked, _
        System.Windows.FlowDirection.RightToLeft, _
        System.Windows.FlowDirection.LeftToRight)
    
    End Sub
    

    ReplaceFlowDirectionMapping 메서드는 FlowDirection 속성에 대한 기본 매핑을 대체합니다.

    OnFlowDirectionChange 메서드는 FlowDirection 속성을 Windows FormsRightToLeft 속성으로 변환합니다.

    cb_CheckedChanged 메서드는 CheckBox 컨트롤의 CheckedChanged 이벤트를 처리합니다. CheckState 속성의 값에 따라 FlowDirection 속성을 할당합니다.

기본 속성 매핑 확장

기본 속성 매핑을 사용하고 고유 매핑으로 확장할 수도 있습니다.

기본 속성 매핑을 확장하려면

  • 다음 코드를 Window1 클래스의 정의에 복사합니다.

    // The ExtendBackgroundMapping method adds a property
    // translator if a mapping already exists.
    private void ExtendBackgroundMapping()
    {
        if (wfHost.PropertyMap["Background"] != null)
        {
            wfHost.PropertyMap["Background"] += new PropertyTranslator(OnBackgroundChange);
        }
    }
    
    // The OnBackgroundChange method assigns a specific image
    // to the hosted control's BackgroundImage property.
    private void OnBackgroundChange(object h, String propertyName, object value)
    {
        WindowsFormsHost host = h as WindowsFormsHost;
        System.Windows.Forms.CheckBox cb = host.Child as System.Windows.Forms.CheckBox;
        ImageBrush b = value as ImageBrush;
    
        if (b != null)
        {
            cb.BackgroundImage = new System.Drawing.Bitmap(@"C:\WINDOWS\Santa Fe Stucco.bmp");
        }
    }
    
    ' The ExtendBackgroundMapping method adds a property
    ' translator if a mapping already exists.
    Private Sub ExtendBackgroundMapping() 
        If wfHost.PropertyMap("Background") IsNot Nothing Then
    
            wfHost.PropertyMap("Background") = PropertyTranslator.Combine( _
            wfHost.PropertyMap("Background"), _
            PropertyTranslator.CreateDelegate( _
                GetType(PropertyTranslator), _
                Me, _
                "OnBackgroundChange"))
        End If
    
    End Sub
    
    
    ' The OnBackgroundChange method assigns a specific image 
    ' to the hosted control's BackgroundImage property.
    Private Sub OnBackgroundChange(ByVal h As Object, ByVal propertyName As String, ByVal value As Object) 
        Dim host As WindowsFormsHost = h 
        Dim cb As System.Windows.Forms.CheckBox = host.Child 
        Dim b As ImageBrush = value 
        
        If Not (b Is Nothing) Then
            cb.BackgroundImage = New System.Drawing.Bitmap("C:\WINDOWS\Santa Fe Stucco.bmp")
        End If
    
    End Sub
    

    ExtendBackgroundMapping 메서드가 사용자 지정 속성 변환기를 기존 Background 속성 매핑에 추가합니다.

    OnBackgroundChange 메서드는 호스트된 컨트롤의 BackgroundImage 속성에 특정 이미지를 할당합니다. 기본 속성 매핑이 적용된 후 OnBackgroundChange 메서드가 호출됩니다.

속성 매핑 초기화

Loaded 이벤트 처리기에서 이전에 설명된 메서드를 호출하여 속성 매핑을 설정합니다.

속성 매핑을 초기화하려면

  1. 다음 코드를 Window1 클래스의 정의에 복사합니다.

    // The WindowLoaded method handles the Loaded event.
    // It enables Windows Forms visual styles, creates
    // a Windows Forms checkbox control, and assigns the
    // control as the child of the WindowsFormsHost element.
    // This method also modifies property mappings on the
    // WindowsFormsHost element.
    private void WindowLoaded(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.Application.EnableVisualStyles();
    
        // Create a Windows Forms checkbox control and assign
        // it as the WindowsFormsHost element's child.
        System.Windows.Forms.CheckBox cb = new System.Windows.Forms.CheckBox();
        cb.Text = "Windows Forms checkbox";
        cb.Dock = DockStyle.Fill;
        cb.TextAlign = ContentAlignment.MiddleCenter;
        cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
        wfHost.Child = cb;
    
        // Replace the default mapping for the FlowDirection property.
        this.ReplaceFlowDirectionMapping();
    
        // Remove the mapping for the Cursor property.
        this.RemoveCursorMapping();
    
        // Add the mapping for the Clip property.
        this.AddClipMapping();
    
        // Add another mapping for the Background property.
        this.ExtendBackgroundMapping();
    
        // Cause the OnFlowDirectionChange delegate to be called.
        wfHost.FlowDirection = System.Windows.FlowDirection.LeftToRight;
    
        // Cause the OnClipChange delegate to be called.
        wfHost.Clip = new RectangleGeometry();
    
        // Cause the OnBackgroundChange delegate to be called.
        wfHost.Background = new ImageBrush();
    }
    
    ' The WindowLoaded method handles the Loaded event.
    ' It enables Windows Forms visual styles, creates 
    ' a Windows Forms checkbox control, and assigns the
    ' control as the child of the WindowsFormsHost element. 
    ' This method also modifies property mappings on the 
    ' WindowsFormsHost element.
    Private Sub WindowLoaded( _
    ByVal sender As Object, _
    ByVal e As RoutedEventArgs)
    
        System.Windows.Forms.Application.EnableVisualStyles()
    
        ' Create a Windows Forms checkbox control and assign 
        ' it as the WindowsFormsHost element's child.
        Dim cb As New System.Windows.Forms.CheckBox()
        cb.Text = "Windows Forms checkbox"
        cb.Dock = DockStyle.Fill
        cb.TextAlign = ContentAlignment.MiddleCenter
        AddHandler cb.CheckedChanged, AddressOf cb_CheckedChanged
        wfHost.Child = cb
    
        ' Replace the default mapping for the FlowDirection property.
        Me.ReplaceFlowDirectionMapping()
    
        ' Remove the mapping for the Cursor property.
        Me.RemoveCursorMapping()
    
        ' Add the mapping for the Clip property.
        Me.AddClipMapping()
    
        ' Add another mapping for the Background property.
        Me.ExtendBackgroundMapping()
    
        ' Cause the OnFlowDirectionChange delegate to be called.
        wfHost.FlowDirection = System.Windows.FlowDirection.LeftToRight
    
        ' Cause the OnClipChange delegate to be called.
        wfHost.Clip = New RectangleGeometry()
    
        ' Cause the OnBackgroundChange delegate to be called.
        wfHost.Background = New ImageBrush()
    
    End Sub
    

    WindowLoaded 메서드는 Loaded 이벤트를 처리하고 다음 초기화를 수행합니다.

    • Windows FormsCheckBox 컨트롤을 만듭니다.

    • 연습에서 이전에 정의한 메서드를 호출하여 속성 매핑을 설정합니다.

    • 매핑된 속성에 초기 값을 할당합니다.

  2. F5 키를 눌러 애플리케이션을 빌드하고 실행합니다. FlowDirection 매핑의 효과를 보려면 확인란을 클릭합니다. 확인란을 클릭하면 레이아웃이 왼쪽에서 오른쪽으로의 방향을 반대로 바꿉니다.

참고 항목