728x90
반응형
WPF - Resources

WPF에서 Resource 의미는?
XAML 내에서 재사용 가능한 객체를 의미하며, 일반적으로 Brush, DataTemplate, ControlTemplate, Storyboard, Style 등이며 보통 다음과 같은 방식으로 선언된다.
<Window.Resources>
<SolidColorBrush x:Key="MyBrush" Color="LightBlue"/>
</Window.Resources>
<Rectangle Fill="{StaticResource MyBrush}" />
주요 Resource 유형
| 유형 | 설명 |
| Brush | 색상 (배경, 선 등) |
| Style | 컨트롤 스타일 지정 |
| Template | 컨트롤 구조 변경 |
| DataTemplate | 데이터 표현 방식 지정 |
| Storyboard | 애니메이션 |
| 객체 리소스 | 사용자 정의 객체 (예: ViewModel, 리스트 등) |
1. Resource 정의위치
- Element.Resources
- Window / UserControl.Resources
- Application.Resources
2. StaticResource vs DynamicResource
| 구분 | StaticResource | DynamicResource |
| 평가 시점 | 컴파일 시 | 런타임 시 |
| 성능 | 빠름 | 느림 |
| 동적 변경 반영 | X | O |
| 주 용도 | 대부분의 리소스 | 테마, 바인딩된 리소스 등 |
<Button Background="{StaticResource MyBrush}" />
<Button Background="{DynamicResource MyBrush}" />
3. Style Resource 예제
<Window.Resources>
<Style x:Key="RoundedButtonStyle" TargetType="Button">
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="Padding" Value="10,5"/>
</Style>
</Window.Resources>
<Button Content="확인" Style="{StaticResource RoundedButtonStyle}" />
4. DataTemplate 예제 (간단한 리스트뷰)
<Window.Resources>
<DataTemplate x:Key="PersonTemplate">
<StackPanel>
<TextBlock Text="{Binding Name}" FontWeight="Bold"/>
<TextBlock Text="{Binding Age}" FontStyle="Italic"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox ItemTemplate="{StaticResource PersonTemplate}" ItemsSource="{Binding People}" />
5. Resource Dictionary 분리 및 병합
- 리소스를 XAML파일로 따로 관리할 수 있다.
- 리소스가 많은 경우 ResourceDictionary를 분리해서 유지관리가 편하도록 구성하는 것이 좋다.
// Colors.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="PrimaryColor" Color="#2196F3" />
</ResourceDictionary>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Colors.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
* 리소스 키와 찾기 방식
리소스를 찾을 때는 WPF가 위에서 아래로, 가까운 곳부터 찾는다.
| 순서 | 예 |
| 1 | 해당 컨트롤 (Button.Resources) |
| 2 | 조상 컨트롤 (StackPanel.Resources) |
| 3 | 창 전체 (Window.Resources) |
| 4 | 앱 전체 (Application.Resources) |
* Nonshared Resources
WPF에서 대부분의 리소스는 기본적으로 공유 (shared)되나 때론 "공유되지않는(non-shared) 리소스"가 필요한 경우도 존재하며 이때 "x:shared="False" "
- WPF 리소스는 기본적으로 한 번 생성되면 동일한 인스턴스를 재사용하며 이것이 Shared Resource (공유 리소스)
- 그러나 x:Shared="False"를 지정하면 리소스를 사용할 때마다 새로운 인스턴스를 생성하며 이게 Non-Shared Resource
| 항목 | Shared (기본) | Non-Shared (x:Shared="False") |
| 인스턴스 | 하나만 생성됨 | 매번 새로 생성됨 |
| 성능 | 더 좋음 | 상대적으로 느림 |
| 사용 예 | Brush, Style, Static 값 | 사용자 정의 객체, ViewModel, 동적 UI 등 |
| 설정 방법 | 기본 설정 | x:Shared="False" 명시 |
<Window.Resources>
<local:Person x:Key="NonSharedPerson" Name="홍길동" x:Shared="False" />
</Window.Resources>
<StackPanel>
<ContentControl Content="{StaticResource NonSharedPerson}" />
<ContentControl Content="{StaticResource NonSharedPerson}" />
</StackPanel>
- ViewModel을 리소스로 등록 - 각 뷰에 개별 인스턴스 필요
- DataTemplate 내부에서 매번 새로운 객체 생성 - 데이터 바인딩과 독립성 유지
- 사용자 정의 컨트롤에 개별 상태 유지 필요 - 공유되면 상태가 꼬임
주의사항
- x:Shared="False"는 오직 StaticResource로 접근할 때만 적용된다.
- DynamicResource에는 사용할 수 없다.
- 인스턴스를 계속 새로 만들기 때문에 메모리나 성능 이슈가 있을 수 있다.
* System Resources
- O/S에서 제공하는 리소스를 WPF에서 쉽게 사용할 수 있도록 만들어진 리소스
- Windows 운영체제의 테마, 색상, 스타일, 크기, 글꼴 등을 반영하는 리소스
- 미리 정의된 키를 통해 XAML에서 접근할 수 있다.
대표적인 시스템 리소스 종류
| 종류 | 설명 | 예시 키 |
| SystemColors | 시스템 색상 | SystemColors.ControlBrushKey |
| SystemFonts | 시스템 글꼴 | SystemFonts.MessageFontFamilyKey |
| SystemParameters | 시스템 DPI, 두께, 크기 등 | SystemParameters.IconWidthKey |
<Button Content="시스템 버튼"
Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<TextBlock Text="시스템 글꼴 사용"
FontFamily="{DynamicResource {x:Static SystemFonts.MessageFontFamilyKey}}" />
<Border BorderThickness="{DynamicResource {x:Static SystemParameters.BorderWidthKey}}"
BorderBrush="Black"
Width="200" Height="50" />
사용하는 이유
- OS 테마 일관성 다크모드, 고대비 모드 등을 자동 반영
- 접근성 향상 시스템 설정에 따라 UI가 적응
- 유지보수성 하드코딩된 값보다 더 유연함
'프로그래밍&IT > C# (Winfrom, WPF)' 카테고리의 다른 글
| [WPF] Shapes, Brushes and Transforms (1) | 2025.08.09 |
|---|---|
| [WPF] Styles and Behaviors (1) | 2025.08.09 |
| [WPF] Commands (0) | 2025.08.06 |
| [WPF] Element Binding (4) | 2025.08.04 |
| [WPF] The Application (1) | 2025.08.04 |