본문 바로가기
C#

WPF DataTemplate과 ItemsControl 완전 이해

by samie 2025. 4. 7.
WPF DataTemplate과 ItemsControl 완전 이해

📦 WPF DataTemplate과 ItemsControl 완전 이해

WPF에서는 데이터 중심 UI 구성에서 DataTemplateItemsControl의 활용이 매우 중요합니다.
이 글에서는 두 기능을 개념부터 실습까지 완전 정복해봅니다.

1. DataTemplate이란?

DataTemplate은 WPF에서 데이터 객체를 화면에 어떻게 표시할지를 정의하는 템플릿입니다.

<DataTemplate>
  <StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Name}" FontWeight="Bold" Margin="5"/>
    <TextBlock Text="{Binding Age}" Margin="5"/>
  </StackPanel>
</DataTemplate>

위와 같이 설정하면, 데이터 객체가 리스트나 리스트박스 등에 표시될 때 자동으로 해당 구조로 렌더링됩니다.

2. ItemsControl이란?

ItemsControl은 여러 개의 항목을 표시하는 기본 컨트롤입니다.
ListBox, ComboBox, ListView 등도 ItemsControl을 상속합니다.

가장 기본적인 형태는 다음과 같습니다.

<ItemsControl ItemsSource="{Binding People}" />

ItemsPanelTemplate으로 레이아웃 제어

<ItemsControl.ItemsPanel>
  <ItemsPanelTemplate>
    <WrapPanel />
  </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

기본은 StackPanel이지만, WrapPanel이나 Grid도 사용 가능해 유연한 배치가 가능합니다.

3. ListBox에서 DataTemplate 활용

🔹 데이터 모델 정의 (C#)


public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

🔹 ViewModel 데이터 바인딩


public ObservableCollection<Person> People { get; set; }

public MainViewModel()
{
    People = new ObservableCollection<Person>
    {
        new Person { Name = "홍길동", Age = 30 },
        new Person { Name = "이순신", Age = 45 },
        new Person { Name = "강감찬", Age = 50 }
    };
}

🔹 XAML에 ListBox와 템플릿 적용


<ListBox ItemsSource="{Binding People}" Margin="10">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}" FontSize="16" FontWeight="Bold" Margin="5"/>
        <TextBlock Text="(" Foreground="Gray"/>
        <TextBlock Text="{Binding Age}" Foreground="Gray"/>
        <TextBlock Text="세)" Foreground="Gray"/>
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

이처럼 아이템 하나당 UI를 커스터마이징할 수 있는 것이 DataTemplate의 핵심입니다.

4. 커스텀 ItemsControl UI 구성

✔️ 다양한 배치와 꾸미기


<ItemsControl ItemsSource="{Binding People}" Margin="10">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Border BorderBrush="LightGray" BorderThickness="1" Margin="5" Padding="10" CornerRadius="5">
        <StackPanel>
          <TextBlock Text="{Binding Name}" FontSize="14" FontWeight="Bold"/>
          <TextBlock Text="{Binding Age, StringFormat='나이: {0}세'}" FontSize="12" Foreground="DarkGray"/>
        </StackPanel>
      </Border>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

이 방식은 카드 형태로 리스트 구성할 때 아주 유용합니다.

5. 마무리 및 다음 글 예고

이번 글에서는 WPF의 핵심 중 하나인 DataTemplate과 ItemsControl을 다뤘습니다.

  • 📌 DataTemplate을 통해 UI 구조를 데이터에 맞게 커스터마이징
  • 📌 ItemsControl로 자유로운 레이아웃 배치 가능

다음 시리즈에서는 ContentTemplate과 HierarchicalDataTemplate을 활용해 트리 구조 UI를 구성하는 방법을 설명드릴 예정입니다.

질문이나 피드백은 댓글로 남겨주세요. 감사합니다! 🙌