상세 컨텐츠

본문 제목

UserControl 생성하기

WPF

by happynuri 2008. 2. 25. 14:37

본문

WPF에서 UserControl은 대부분의 경우 xaml 파일을 형식으로 생성합니다. 실제로 xaml의 종류 자세히 나누어 보면 Application, Window, Page, UserControl 등등 여러 가지 형식으로 존재합니다. 확장자가 xaml이라고 해서 다 같은 xaml이 아니라는 얘기지요. xaml이 어떤 형식인지를 알려면 xaml파일의 루트 요소 혹은 코드비하인드 파일의 기본 클래스를 가지고 판단을 해야 합니다. (사실 Blend 혹은 Visual Studio에서 기본적으로 만들어지는 xaml 파일의 이름을 가지고 눈치껏 판단하는 경우가 더 많습니다.ㅎㅎ. App.xaml 요렇게 이름이 붙었다면 보나마나 Application 형식이고, Windows1.xaml 이라고 이름이 되어 있으면 요건 Window형식의 xaml입니다.)
 
xaml 파일의 종류를 정리해 보면 다음과 같습니다.
1. Application
   - 루트요소 : <Application>
   - 기본 클래스 형식 : System.Windows.Application
   - 기본적으로 붙여지는 이름 : App.xaml
2. Window
   - 루트요소 : <Window>
   - 기본 클래스 형식 : System.Windows.Window
   - 기본적으로 붙여지는 이름 : Window1.xaml, Window2.xaml …
3. Page
   - 루트요소 : <Page>
   - 기본 클래스 형식 : System.Windows.Controls.Page
   - 기본적으로 붙여지는 이름 : Page1.xaml, Page2.xaml, …
4. UserControl
   - 루트요소 : <UserControl>
   - 기본 클래스 형식 : System.Windows.Controls.UserControl
   - 기본적으로 붙여지는 이름 : UserControl1, UserContro2, …
5. ResourceDictionary
   - 루트요소 : <ResourceDictionary>
   - 기본 클래스 형식 : System.Windows.ResourceDictionary
   - 기본적으로 붙여지는 이름 : Blend : ResourceDictionary1.xaml, ResourceDictionary2.xaml, …
                                Visual Studio : Dictionary1.xaml, Dictionary2.xaml, …
   - 비고 : 코드비하인드 파일 없음
6. FlowDocument
   - 루트요소 : <FlowDocument>
   - 기본 클래스 형식 : System.Windows.Documents.FlowDocument
   - 기본적으로 붙여지는 이름 : FlowDocument1.xaml, FlowDocument2.xaml, …
   - 비고 : 코드비하인드 파일 없음
7. PageFunction
   - 루트요소 : <PageFunction>
   - 기본 클래스 형식 : System.Windows.Navigation.PageFunction<T>
   - 기본적으로 붙여지는 이름 : PageFunction1.xaml,  PageFunction2.xaml, …
 
UserControl은 xaml을 이용하므로 Blend나 Visual Studio의 디자이너를 이용할 수 있습니다. UserControl은 기존의 컨트롤을 여러 개를 조합해서 하나의 새로운 컨트롤을 만들기 위해 주로 사용합니다. 반면 CustomContol은 xaml파일을 사용하지 않고 cs 파일로만 작성합니다. 이번 글에서는 UserControl의 작성 및 사용방법에 대해서만 다룹니다.
* UserControl 생성
1. UserControl을 생성하려면 우선 프로젝트에 UserControl형식의 xaml파일을 추가합니다.
- Blend의 경우
 
 
- Visual Studio의 경우
 
 
2. xaml파일에 자신만의 컨트롤을 디자인
 
 
* UserControl 사용하기
1. UserControl을 사용하려는 Page나 Window xaml 파일에서 xmlns로 네임스페이스를 지정합니다. 이때 네임스페이스의 prefix를 지정합니다.
2. 그리고 네임스페이스의 prefix를 이용하여 UserControl의 이름을 요소로 사용하면 됩니다. 예제 소스는 아래와 같습니다. 두꺼운 글씨로 표시된 곳이 UserControl을 사용하기 위해 필요한 소스입니다.
<Page x:Class="ControlGallery.ButtonGallery"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uc="clr-namespace:ControlGallery"
    Title="ButtonGallery"
    >
    <Grid>
      <uc:Button001 Width="150" Height="60" />
    </Grid>
</Page>
 
Button UserControl 만들어서 xbap응용프로그램에서 사용한 화면입니다.
 

관련글 더보기

댓글 영역