최근 업무가 바빠서 오랜만에 글을 쓰네요 ㅠ 좀 더 자주 쓸 수 있도록 분발해야겠습니다 👿
오늘은 WPF 내에서 리소스 활용을 위해 사용하는 StaticResource와 DynamicResource에 대해 간단하게 알아보려 합니다.
저번 기술면접에서 다음과 같은 질문을 받았었지요 ㅎ
"StaticResouce와 DynamicResource에 대해 아는대로 말씀해주시겠어요?"
면접에 등장할만큼 WPF 개발자에게는 기본적인 지식이고, 다른사람들에게 간단하게 설명할 수 있게 한번 정리를 해야할꺼 같아서 이번 글을 작성하게 되었습니다.
MSDN에는 다음과 같이 정의되어 있습니다.
StaticResource
Provides a value for any XAML property attribute by looking up a reference to an already defined resource. Lookup behavior for that resource is analogous to load-time lookup, which will look for resources that were previously loaded from the markup of the current XAML page as well as other application sources, and will generate that resource value as the property value in the run-time objects.
MSDN 참고 (https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/staticresource-markup-extension)
DynamicResource
Provides a value for any XAML property attribute by deferring that value to be a reference to a defined resource. Lookup behavior for that resource is analogous to run-time lookup.
MSDN 참고 (https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/dynamicresource-markup-extension)
위 구문을 통해 다음과 같은 특징을 알 수 있습니다.
- 둘 다 정의된 리소스를 참조하여 값을 제공한다.
- StaticResource는 load-time 조회와 유사하다.
- DynamicResource는 run-time 조회와 유사하다.
자 그럼 예제를 통해 어떤 차이점이 있는지 알아봅시다
<Window
x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="200"
Height="300"
mc:Ignorable="d">
<Window.Resources>
<ResourceDictionary>
<SolidColorBrush x:Key="brush" Color="Red" />
</ResourceDictionary>
</Window.Resources>
<StackPanel>
<Label Background="{StaticResource brush}" Content="StaticResource" />
<Label Background="{DynamicResource brush}" Content="DynamicResource" />
<Button
Width="100"
Height="100"
Margin="0,5"
Click="Button_Click"
Content="Switch" />
</StackPanel>
</Window>
using System.Windows;
using System.Windows.Media;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Resources["brush"] = new SolidColorBrush(Colors.Yellow);
}
}
}
위 xaml 코드와 code-behind를 보면 다음을 알 수 있습니다.
- "brush" key를 가진 SolidColorBrush가 존재한다.
- 배치된 Label 2개는 Background에 "brush" 리소스를 각각 StaticResoucre와 DynamicResource 형태로 참조한다.
- Button을 클릭하면 "brush" 키를 가진 리소스가 변경된다.
실행을 하면 다음과 같은 결과를 얻습니다.
DynamicResouce를 통해 참조한 Background만이 색이 변경되는 것을 볼 수 있습니다.
위 예제코드와 실행결과를 보면 DynamiceResource와 StaticResource의 차이는 다음과 같다는 것을 알 수 있습니다.
- StaticResource는 View 로드 시에만 Resources에서 리소스를 가져와 적용한다.
- DynamicResource를 통해 참조를 하게되면 Reousces에서 변경이 일어날 때 해당 리소스를 다시 가져와서 적용하게 됨.
- StaticResouce를 사용할 경우 Resources에 해당 리소스가 없으면 에러를 발생시키지만, DynamicResource는 리소스가 없더라도 에러가 발생하지 않으며, 해당 리소스가 생성되면 다시 가져와서 적용하게 된다.