본문 바로가기
C#(CSharp)/WPF

WPF에서 윈도우 Form Control 사용하기 (WPF Hosting the Windows Forms Control)

by swconsulting 2015. 3. 9.

1. 프로젝트에 아래 레퍼런스를 추가한다.


 - WindowsFormsIntegration

 - System.Windows.Forms


2. XAML에 아래 레퍼런스를 추가한다.

<추가 xmlns>

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"


<XAML 선언부분 추가> 

<Window x:Class="Wpf_MySQL.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

 

        Title="MainWindow" Height="350" Width="525">



3. 실제 컨트롤을 아래 xaml 처러 추가해서 사용하면 된다.

        <WindowsFormsHost Grid.Row="0">

            <wf:DataGridView x:Name="xdgView"></wf:DataGridView>

        </WindowsFormsHost>


<전체 XAML>

<Window x:Class="Wpf_MySQL.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

        Title="MainWindow" Height="350" Width="525">

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="1*"></RowDefinition>

            <RowDefinition Height="40"></RowDefinition>

        </Grid.RowDefinitions>

       

        <WindowsFormsHost Grid.Row="0">

            <wf:DataGridView x:Name="xdgView"></wf:DataGridView>

        </WindowsFormsHost>

       

        <Border Grid.Row="1">

            <Grid>

                <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="1*" />

                    <ColumnDefinition Width="1*" />

                </Grid.ColumnDefinitions>

                <Button Grid.Column="0" Click="Save_Button_Click"> Save </Button>

                <Button Grid.Column="1" Click="Delete_Button_Click" > Delete </Button>

            </Grid>

        </Border>       

    </Grid>

 

</Window>



첨부한 샘플 코드 동작하기 위해서는 DB와 연동이 되어야 합니다. 

저는 OpenSource인 MySql을 이용했습니다.


1)테스트 데이타 베이스 테이블 생성및 데이터 추가

use test;


CREATE TABLE IF NOT EXISTS `items` (

  `ItemNumber` int(11) NOT NULL,

  `ItemName` varchar(100) NOT NULL,

  `Price` double NOT NULL,

  `AvailableQuantity` int(11) NOT NULL,

  `Updated_Dt` datetime NOT NULL,

  PRIMARY KEY (`ItemNumber`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;



INSERT INTO `items` (`ItemNumber`, `ItemName`, `Price`, `AvailableQuantity`, `Updated_Dt`) VALUES

(1, 'Papers', 11, 5, '2010-03-22 14:59:33'),

(2, 'Pencils', 2, 10, '2010-03-22 15:01:17'),

(3, 'Staplers', 5.3, 1, '2010-03-22 15:01:49'),

(4, 'Books', 12, 7, '2010-03-22 14:59:34');


 

select * from items;


2) MySQL에서 다운 받은 레퍼런스 추가
using System.Configuration;
using MySql.Data.MySqlClient;

3) C# 프로젝트 설정에 DB 연결 문자열 추가

<appSettings>

    <add key="ConnectionString" value="SERVER=localhost;DATABASE=test;UID=root;PASSWORD=***;"/>

</appSettings>


이외에는 첨부한 소스코드 참고하세요

Wpf_MySQL.zip