연습: WPF에서 Windows Forms 컨트롤 정렬
업데이트: 2010년 8월
이 연습에서는 WPF 레이아웃 기능을 사용하여 혼합 응용 프로그램에서 Windows Forms 컨트롤을 정렬하는 방법을 보여 줍니다.
이 연습에서 수행할 작업은 다음과 같습니다.
프로젝트 만들기
기본 레이아웃 설정 사용
콘텐츠에 맞게 크기 조정
절대 위치 사용
명시적으로 크기 지정
레이아웃 속성 설정
Z 순서 제한 이해
도킹
표시 유형 설정
확장되지 않는 컨트롤 호스팅
배율 조정
회전
안쪽 여백 및 여백 설정
동적 레이아웃 컨테이너 사용
이 연습에서 설명하는 작업의 전체 코드 목록은 Arranging Windows Forms Controls in WPF 샘플을 참조하십시오.
연습을 마치면 WPF 기반 응용 프로그램에서의 Windows Forms 레이아웃 기능을 이해할 수 있게 됩니다.
사전 요구 사항
이 연습을 완료하려면 다음 구성 요소가 필요합니다.
- Visual Studio 2010.
프로젝트 만들기
프로젝트를 만들고 설정하려면
WpfLayoutHostingWf라는 WPF 응용 프로그램 프로젝트를 만듭니다.
솔루션 탐색기에서 다음 어셈블리에 대한 참조를 추가합니다.
WindowsFormsIntegration
System.Windows.Forms
System.Drawing
MainWindow.xaml을 두 번 클릭하여 XAML 뷰에서 엽니다.
Window 요소에서 다음 Windows Forms 네임스페이스 매핑을 추가합니다.
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Grid 요소에서 ShowGridLines 속성을 true로 설정하고 다섯 개의 행과 세 개의 열을 정의합니다.
<Grid ShowGridLines="true"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions>
기본 레이아웃 설정 사용
기본적으로 WindowsFormsHost 요소에서는 호스팅된 Windows Forms 컨트롤의 레이아웃을 처리합니다.
기본 레이아웃 설정을 사용하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Default layout. --> <Canvas Grid.Row="0" Grid.Column="0"> <WindowsFormsHost Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. Windows Forms System.Windows.Forms.Button 컨트롤이 Canvas에 나타납니다. 호스팅된 컨트롤의 크기가 해당 콘텐츠에 맞게 조정되고 WindowsFormsHost 요소의 크기가 호스팅된 컨트롤에 맞게 조정됩니다.
콘텐츠에 맞게 크기 조정
WindowsFormsHost 요소에서는 호스팅된 컨트롤이 해당 콘텐츠를 적절하게 표시할 수 있는 크기인지 확인합니다.
콘텐츠에 맞게 크기를 조정하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Sizing to content. --> <Canvas Grid.Row="1" Grid.Column="0"> <WindowsFormsHost Background="Orange"> <wf:Button Text="Windows Forms control with more content" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas> <Canvas Grid.Row="2" Grid.Column="0"> <WindowsFormsHost FontSize="24" Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. 새로운 두 단추 컨트롤의 크기가 긴 텍스트 문자열과 큰 글꼴 크기를 적절하게 표시할 수 있도록 조정되고 WindowsFormsHost 요소의 크기가 호스팅된 컨트롤에 맞게 조정됩니다.
절대 위치 사용
절대 위치를 사용하여 UI(사용자 인터페이스)에서 임의의 위치에 WindowsFormsHost 요소를 배치할 수 있습니다.
절대 위치를 사용하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Absolute positioning. --> <Canvas Grid.Row="3" Grid.Column="0"> <WindowsFormsHost Canvas.Top="20" Canvas.Left="20" Background="Yellow"> <wf:Button Text="Windows Forms control with absolute positioning" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. WindowsFormsHost 요소가 표 셀의 위쪽에서 20픽셀, 왼쪽에서 20픽셀 떨어진 위치에 배치됩니다.
명시적으로 크기 지정
Width 및 Height 속성을 사용하여 WindowsFormsHost 요소의 크기를 지정할 수 있습니다.
크기를 명시적으로 지정하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Explicit sizing. --> <Canvas Grid.Row="4" Grid.Column="0"> <WindowsFormsHost Width="50" Height="70" Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. WindowsFormsHost 요소가 기본 레이아웃 설정보다 작은 너비 50픽셀, 높이 70픽셀의 크기로 설정됩니다. Windows Forms 컨트롤의 콘텐츠가 적절하게 다시 정렬됩니다.
레이아웃 속성 설정
호스팅된 컨트롤의 레이아웃 관련 속성은 항상 WindowsFormsHost 요소의 속성을 사용하여 설정합니다. 레이아웃 속성을 직접 호스팅된 컨트롤에 대해 설정하면 원치 않는 결과가 발생합니다.
XAML에서 호스팅된 컨트롤에 대해 레이아웃 관련 속성을 설정해도 아무런 영향을 주지 않습니다.
호스팅된 컨트롤의 속성을 설정한 결과를 확인하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Setting hosted control properties directly. --> <Canvas Grid.Row="0" Grid.Column="1"> <WindowsFormsHost Width="160" Height="50" Background="Yellow"> <wf:Button Name="button1" Click="button1_Click" Text="Click me" FlatStyle="Flat" BackColor="Green"/> </WindowsFormsHost> </Canvas>
솔루션 탐색기에서 MainWindow.xaml.vb 또는 MainWindow.xaml.cs를 두 번 클릭하여 코드 편집기에서 엽니다.
다음 코드를 MainWindow 클래스 정의에 복사합니다.
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Dim b As System.Windows.Forms.Button = sender b.Top = 20 b.Left = 20 End Sub
private void button1_Click(object sender, EventArgs e ) { System.Windows.Forms.Button b = sender as System.Windows.Forms.Button; b.Top = 20; b.Left = 20; }
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다.
Click me 단추를 클릭합니다. button1_Click 이벤트에서 호스팅된 컨트롤의 Top 및 Left 속성을 설정합니다. 그러면 WindowsFormsHost 요소 내에서 호스팅된 컨트롤의 위치가 변경됩니다. 호스트에서는 동일한 화면 크기를 유지하지만 호스팅된 컨트롤이 잘립니다. 대신 호스팅된 컨트롤에서 항상 WindowsFormsHost 요소를 채워야 합니다.
Z 순서 제한 이해
보이는 WindowsFormsHost 요소는 항상 다른 WPF 요소 위에 그려지고 z 순서의 영향을 받지 않습니다.
Z 순서 제한을 확인하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Z-order demonstration. --> <Canvas Grid.Row="1" Grid.Column="1"> <Label Content="A WPF label" FontSize="24"/> <WindowsFormsHost Canvas.Top="20" Canvas.Left="20" Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. WindowsFormsHost 요소가 레이블 요소 위에 그려집니다.
도킹
WindowsFormsHost 요소에서는 WPF 도킹을 지원합니다. Dock 연결 속성을 사용하여 DockPanel 요소에서 호스팅된 컨트롤을 도킹하도록 설정합니다.
호스팅된 컨트롤을 도킹하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Docking a WindowsFormsHost element. --> <DockPanel LastChildFill="false" Grid.Row="2" Grid.Column="1"> <WindowsFormsHost DockPanel.Dock="Right" Canvas.Top="20" Canvas.Left="20" Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> </DockPanel>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. WindowsFormsHost 요소가 DockPanel 요소의 오른쪽에 도킹됩니다.
표시 유형 설정
WindowsFormsHost 요소의 Visibility 속성을 사용하여 Windows Forms 컨트롤에서 해당 요소를 보이지 않거나 축소되도록 만들 수 있습니다. 컨트롤이 보이지 않는 경우 컨트롤이 표시되지는 않지만 레이아웃 공간을 계속 차지합니다. 컨트롤이 축소되는 경우 컨트롤이 표시되지도 않고 레이아웃 공간을 차지하지도 않습니다.
호스팅된 컨트롤의 표시 유형을 설정하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Setting Visibility to hidden and collapsed. --> <StackPanel Grid.Row="3" Grid.Column="1"> <Button Name="button2" Click="button2_Click" Content="Click to make invisible" Background="OrangeRed"/> <WindowsFormsHost Name="host1" Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> <Button Name="button3" Click="button3_Click" Content="Click to collapse" Background="OrangeRed"/> </StackPanel>
MainWindow.xaml.vb 또는 MainWindow.xaml.cs에서 클래스 정의에 다음 코드를 복사합니다.
Private Sub button2_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Me.host1.Visibility = Windows.Visibility.Hidden End Sub Private Sub button3_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Me.host1.Visibility = Windows.Visibility.Collapsed End Sub
private void button2_Click(object sender, EventArgs e) { this.host1.Visibility = Visibility.Hidden; } private void button3_Click(object sender, EventArgs e) { this.host1.Visibility = Visibility.Collapsed; }
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다.
Click to make invisible 단추를 눌러 WindowsFormsHost 요소를 보이지 않게 만듭니다.
Click to collapse 단추를 눌러 WindowsFormsHost 요소를 레이아웃에서 완전히 숨깁니다. Windows Forms 컨트롤이 축소되는 경우 주변 요소가 해당 공간을 차지하도록 다시 정렬됩니다.
확장되지 않는 컨트롤 호스팅
일부 Windows Forms 컨트롤은 고정된 크기를 가지며 레이아웃에서 사용 가능한 공간을 채우도록 확장되지 않습니다. 예를 들어 MonthCalendar 컨트롤은 고정된 공간에 월을 표시합니다.
확장되지 않는 컨트롤을 호스팅하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Hosting a control that does not stretch. --> <!-- The MonthCalendar has a discrete size. --> <StackPanel Grid.Row="4" Grid.Column="1"> <Label Content="A WPF element" Background="OrangeRed"/> <WindowsFormsHost Background="Yellow"> <wf:MonthCalendar/> </WindowsFormsHost> <Label Content="Another WPF element" Background="OrangeRed"/> </StackPanel>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. WindowsFormsHost 요소가 표 행에서 가운데에 맞춰지지만 사용 가능한 공간을 채우도록 확장되지 않습니다. 창의 크기가 충분한 경우 호스팅된 MonthCalendar 컨트롤에서 두 개 이상의 월을 표시하지만 이러한 값이 행의 가운데에 정렬됩니다. WPF 레이아웃 엔진에서는 사용 가능한 공간을 채우도록 크기 조정될 수 없는 요소를 가운데에 정렬합니다.
배율 조정
WPF 요소와 달리 대부분의 Windows Forms 컨트롤은 계속해서 확장될 수 없습니다. WindowsFormsHost 요소에서는 가능한 경우 호스팅된 컨트롤의 배율을 조정합니다.
호스팅된 컨트롤의 배율을 조정하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Scaling transformation. --> <StackPanel Grid.Row="0" Grid.Column="2"> <StackPanel.RenderTransform> <ScaleTransform CenterX="0" CenterY="0" ScaleX="0.5" ScaleY="0.5" /> </StackPanel.RenderTransform> <Label Content="A WPF UIElement" Background="OrangeRed"/> <WindowsFormsHost Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> <Label Content="Another WPF UIElement" Background="OrangeRed"/> </StackPanel>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. 호스팅된 컨트롤과 주위 요소가 계수 0.5만큼 배율 조정됩니다. 그러나 호스팅된 컨트롤의 글꼴은 배율 조정되지 않습니다.
회전
WPF 요소와 달리 Windows Forms 컨트롤에서는 회전을 지원하지 않습니다. 회전 변환을 적용할 때 WindowsFormsHost 요소는 다른 WPF 요소와 함께 회전되지 않습니다. 180도 이외의 회전 값을 지정하면 LayoutError 이벤트가 발생합니다.
혼합 응용 프로그램에서 회전의 결과를 확인하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Rotation transformation. --> <StackPanel Grid.Row="1" Grid.Column="2"> <StackPanel.RenderTransform> <RotateTransform CenterX="200" CenterY="50" Angle="180" /> </StackPanel.RenderTransform> <Label Content="A WPF element" Background="OrangeRed"/> <WindowsFormsHost Background="Yellow"> <wf:Button Text="Windows Forms control" FlatStyle="Flat"/> </WindowsFormsHost> <Label Content="Another WPF element" Background="OrangeRed"/> </StackPanel>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. 호스팅된 컨트롤은 회전되지 않지만 주변 요소는 180도씩 회전합니다. 창의 크기를 조정해야 요소가 표시되는 경우도 있습니다.
안쪽 여백 및 여백 설정
WPF 레이아웃에서 안쪽 여백 및 여백은 Windows Forms에서의 안쪽 여백 및 여백과 유사합니다. WindowsFormsHost 요소에서 Padding 및 Margin 속성을 설정하면 됩니다.
호스팅된 컨트롤의 안쪽 여백 및 여백을 설정하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Padding. --> <Canvas Grid.Row="2" Grid.Column="2"> <WindowsFormsHost Padding="0, 20, 0, 0" Background="Yellow"> <wf:Button Text="Windows Forms control with padding" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas> ... <!-- Margin. --> <Canvas Grid.Row="3" Grid.Column="2"> <WindowsFormsHost Margin="20, 20, 0, 0" Background="Yellow"> <wf:Button Text="Windows Forms control with margin" FlatStyle="Flat"/> </WindowsFormsHost> </Canvas>
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. 안쪽 여백 및 여백 설정은 Windows Forms에서 적용되는 것과 동일한 방식으로 호스팅된 Windows Forms 컨트롤에 적용됩니다.
동적 레이아웃 컨테이너 사용
Windows Forms에서는 FlowLayoutPanel 및 TableLayoutPanel이라는 두 가지 동적 레이아웃 컨테이너를 제공합니다. 또한 이러한 컨테이너를 WPF 레이아웃에서 사용할 수도 있습니다.
동적 레이아웃 컨테이너를 사용하려면
다음 XAML을 Grid 요소에 복사합니다.
<!-- Flow layout. --> <DockPanel Grid.Row="4" Grid.Column="2"> <WindowsFormsHost Name="flowLayoutHost" Background="Yellow"> <wf:FlowLayoutPanel/> </WindowsFormsHost> </DockPanel>
MainWindow.xaml.vb 또는 MainWindow.xaml.cs에서 클래스 정의에 다음 코드를 복사합니다.
Private Sub InitializeFlowLayoutPanel() Dim flp As System.Windows.Forms.FlowLayoutPanel = Me.flowLayoutHost.Child flp.WrapContents = True Const numButtons As Integer = 6 Dim i As Integer For i = 0 To numButtons Dim b As New System.Windows.Forms.Button() b.Text = "Button" b.BackColor = System.Drawing.Color.AliceBlue b.FlatStyle = System.Windows.Forms.FlatStyle.Flat flp.Controls.Add(b) Next i End Sub
private void InitializeFlowLayoutPanel() { System.Windows.Forms.FlowLayoutPanel flp = this.flowLayoutHost.Child as System.Windows.Forms.FlowLayoutPanel; flp.WrapContents = true; const int numButtons = 6; for (int i = 0; i < numButtons; i++) { System.Windows.Forms.Button b = new System.Windows.Forms.Button(); b.Text = "Button"; b.BackColor = System.Drawing.Color.AliceBlue; b.FlatStyle = System.Windows.Forms.FlatStyle.Flat; flp.Controls.Add(b); } }
InitializeFlowLayoutPanel 메서드에 대한 호출을 생성자에 추가합니다.
Public Sub New() InitializeComponent() Me.InitializeFlowLayoutPanel() End Sub
public MainWindow() { InitializeComponent(); this.InitializeFlowLayoutPanel(); }
F5 키를 눌러 응용 프로그램을 빌드 및 실행합니다. WindowsFormsHost 요소가 DockPanel을 채우고 FlowLayoutPanel에서 해당 자식 컨트롤을 기본 FlowDirection으로 정렬합니다.
참고 항목
참조
개념
WindowsFormsHost 요소에 대한 레이아웃 고려 사항
연습: WPF에서 Windows Forms 복합 컨트롤 호스팅
연습: Windows Forms에서 WPF 복합 컨트롤 호스팅
기타 리소스
Arranging Windows Forms Controls in WPF 샘플
변경 기록
날짜 |
변경 내용 |
이유 |
---|---|---|
2010년 8월 |
Visual Studio 2010에 대한 내용을 업데이트했습니다. |
고객 의견 |