WPF 리소스의 목적과 역할
WPF에서 리소스는 스타일, 페인트, 템플릿 등의 재사용 가능한 객체를 중앙 집중적으로 관리하는 기능입니다. 이를 통해 반복적인 코드 작성을 줄이고, 사용자 인터페이스의 전반적인 색상, 폰트, 레이아웃 설정 등을 단일 위치에서 수정할 수 있어 유지보수가 용이합니다.
리소스 정의 및 사용 방식
리소스는 일반적으로 XAML에서 정의되며, <Window.Resources> 또는 <Application.Resources> 내부에 선언됩니다. 각 요소는 Resources 속성을 가지며, 이는 ResourceDictionary 타입의 컬렉션입니다. 리소스는 유일한 키로 식별되며, x:Key 속성을 통해 지정합니다.
<Window.Resources>
<ImageBrush x:Key="BackgroundPattern"
TileMode="Tile"
ViewportUnits="Absolute"
Viewport="0 0 32 32"
ImageSource="icon.png"
Opacity="0.4" />
</Window.Resources>
정적 리소스와 동적 리소스 차이
정적 리소스({StaticResource})는 창 생성 시 한 번만 해석되어 성능이 우수합니다. 반면 동적 리소스({DynamicResource})는 리소스가 변경될 때마다 자동으로 갱신되므로 실시간 반영이 가능합니다.
<Button Background="{StaticResource BackgroundPattern}"
Content="패턴 적용 버튼" />
<Button Background="{DynamicResource BackgroundPattern}"
Content="실시간 패턴 변경" />
리소스 계층 구조
WPF는 요소 트리 상에서 위로 올라가며 리소스를 검색합니다. 즉, 현재 요소에 없는 리소스는 부모 요소의 리소스 사전에서 찾습니다. 이 특성 덕분에 리소스를 최상위 요소(예: Window)에 정의하면 전체 애플리케이션에서 공유할 수 있습니다.
다른 리소스 사전에서도 동일한 키를 사용할 수 있으며, 우선순위는 더 가까운 요소의 리소스가 높습니다.
<StackPanel>
<Button Background="{StaticResource BackgroundPattern}" />
<Button>
<Button.Resources>
<ImageBrush x:Key="BackgroundPattern" ImageSource="error.png" />
</Button.Resources>
<TextBlock Text="내부 리소스 사용" />
</Button>
</StackPanel>
비공유 리소스 설정
기본적으로 리소스는 공유된 인스턴스를 사용하지만, x:Shared="False"를 지정하면 매번 새로운 인스턴스를 생성합니다.
<ImageBrush x:Key="UniqueBrush" x:Shared="False" ImageSource="data.png" />
코드 내에서 리소스 접근
코드에서 리소스를 참조하려면 FindResource() 또는 TryFindResource() 메서드를 사용합니다.
private void ChangeBackground_Click(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
var brush = (ImageBrush)button.FindResource("BackgroundPattern");
if (brush != null)
{
button.Background = brush;
}
}
애플리케이션 범위 리소스
전체 앱에서 공유되는 리소스는 App.xaml 파일의 Application.Resources 섹션에 정의합니다.
<Application x:Class="MyApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<SolidColorBrush x:Key="PrimaryColor" Color="Blue" />
</Application.Resources>
</Application>
시스템 리소스 활용
SystemColors, SystemFonts, SystemParameters 클래스는 운영체제의 현재 설정을 제공합니다. 예를 들어, 사용자의 테마 색상이나 폰트 크기를 반영할 수 있습니다.
<Label Foreground="{x:Static SystemColors.WindowTextBrush}"
Content="시스템 색상 사용" />
<Label Foreground="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"
Content="동적 시스템 색상" />
리소스 사전 분리
다수의 프로젝트에서 공통 리소스를 사용하려면 별도의 .xaml 파일로 리소스 사전을 분리하고, MergedDictionaries를 통해 통합할 수 있습니다.
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>