[C#][WPF] Resource

LimJaeJun·2024년 3월 19일

WPF

목록 보기
7/12

WPF는 데이터를 리소스 형태로 저장할 수 있다.
컨트롤이나 윈도우를 로컬 혹은 전역으로 저장할 수 있다.

이러한 개념들은 스타일과 템플릿에서 자주 사용된다.

StaticResoure와 DynamicResource

StaticResource (정적 리소스)

StaticResource는 XAML에서 리소스를 정적으로 참조할 때 사용됩니다.
한 번 정의된 리소스를 여러 곳에서 참조할 때 유용합니다.
정적으로 결정되며, 한 번 리소스가 로드되면 변경되지 않습니다.

예제 코드

<Window x:Class="WPF_Resource.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Resource" 
		xmlns:sys="clr-namespace:System;assembly=mscorlib"
		mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
	
	<Window.Resources>
		<SolidColorBrush x:Key="MyBrush" Color="Red"/>
	</Window.Resources>

	<Grid>
		<Grid>
			<Button Content="Button 1" Background="{StaticResource MyBrush}" Width="100" Height="100"
					HorizontalAlignment="Left" VerticalAlignment="Top"/>
			<Button Content="Button 2" Background="{StaticResource MyBrush}" Width="100" Height="100"
					HorizontalAlignment="Right" VerticalAlignment="Top"/>
		</Grid>
	</Grid>
</Window>

결과

DynamicResource (동적 리소스)

DynamicResource는 런타임에 리소스를 동적으로 참조할 때 사용됩니다.
런타임에 리소스가 변경될 수 있는 경우 유용합니다. 즉, 리소스가 다시 로드될 때 해당 변경 사항이 반영됩니다.

예제 코드

<Window x:Class="WPF_Resource.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Resource" 
		xmlns:sys="clr-namespace:System;assembly=mscorlib"
		mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
	
	<Window.Resources>
		<SolidColorBrush x:Key="MyBrush" Color="Red"/>
	</Window.Resources>

	<Grid>

		<Grid>
			<Button Content="Button 1" Background="{DynamicResource MyBrush}" Width="100" Height="100"
					HorizontalAlignment="Left" VerticalAlignment="Top"/>
			<Button Content="Button 2" Background="{DynamicResource MyBrush}" Width="100" Height="100"
					HorizontalAlignment="Right" VerticalAlignment="Top"/>
			
		</Grid>

		<Grid>
			<Grid.Resources>
				<SolidColorBrush x:Key="MyBrush" Color="Blue"/>
			</Grid.Resources>
			<Grid>
				<Button Content="Button 1" Background="{DynamicResource MyBrush}" Width="100" Height="100"
						HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
				<Button Content="Button 2" Background="{DynamicResource MyBrush}" Width="100" Height="100"
						HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
			</Grid>
		</Grid>
	</Grid>
</Window>

결과

차이점

StaticResource는 정적으로 결정되며, 한 번 로드된 후 변경되지 않습니다.
DynamicResource는 런타임에 동적으로 변경될 수 있으며, 리소스가 변경되면 해당 변경 사항이 즉시 반영됩니다.
StaticResource는 더 효율적이지만, 변경이 필요한 경우 DynamicResource를 사용합니다. 동적 리소스가 런타임에 변경될 가능성이 있는 경우 동적 리소스가 적합합니다.

다양한 리소스 타입

예제 코드

<Window x:Class="WPF_Resource.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Resource" 
		xmlns:sys="clr-namespace:System;assembly=mscorlib"
		mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
	<Window.Resources>
		<SolidColorBrush x:Key="MyBrush" Color="Red"/>
		<sys:String x:Key="ComboBoxTitle">Fruits:</sys:String>

		<x:Array x:Key="ComboBoxItems" Type="sys:String">
			<sys:String>Apple</sys:String>
			<sys:String>Banana</sys:String>
			<sys:String>Mango</sys:String>
		</x:Array>

		<LinearGradientBrush x:Key="WindowBackgroundBrush">
			<GradientStop Offset="0" Color="Silver"/>
			<GradientStop Offset="1" Color="Gray"/>
		</LinearGradientBrush>
	</Window.Resources>

	<Grid>
		<StackPanel Margin="10">
			<Label Content="{StaticResource ComboBoxTitle}" />
			<ComboBox ItemsSource="{StaticResource ComboBoxItems}" />
		</StackPanel>
	</Grid>
</Window>

sys:String 사용하기

위 코드를 작성하면 에러가 뜬다.
이를 해결하기 위해 해당 코드에 Alt + Enter를 눌러 해결이 가능하다.

Window 속성에

xmlns:sys="clr-namespace:System;assembly=mscorlib"

을 추가한다.

결과

로컬 리소스와 어플리케이션 리소스

로컬 리소스

생성된 컨트롤 범위 내에서만 해당 리소스에 접근할 수 있다.

예제 코드

<Window x:Class="WPF_Resource.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Resource" 
		xmlns:sys="clr-namespace:System;assembly=mscorlib"
		mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
	<Window.Resources>
		
	</Window.Resources>

	<StackPanel Margin="10">
		<StackPanel.Resources>
			<sys:String x:Key="ComboBoxTitle">StackPanel's Resource</sys:String>
		</StackPanel.Resources>
		<Label Content="{StaticResource ComboBoxTitle}"
			   FontSize="50"
			   FontWeight="Bold"
			   HorizontalAlignment="Center"/>
	</StackPanel>
	
</Window>

StackPanel내에 생성된 컨트롤러는 Resources에 접근할 수 있지만
외부에 생성된 컨트롤러는 접근할 수 없다.

결과

CodeBehind의 리소스

App.xaml 리소스

<Application x:Class="WPF_Resource.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WPF_Resource"
			 xmlns:sys="clr-namespace:System;assembly=mscorlib"
			 StartupUri="MainWindow.xaml">
	<Application.Resources>
		<sys:String x:Key="strApp">Hello, Application world!</sys:String>
	</Application.Resources>
</Application>

Window 리소스

<Window x:Class="WPF_Resource.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Resource" 
		xmlns:sys="clr-namespace:System;assembly=mscorlib"
		mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
	<Window.Resources>
		<sys:String x:Key="strWindow">Hello, Window world!</sys:String>
	</Window.Resources>
	<DockPanel Margin="10" Name="pnlMain">
		<DockPanel.Resources>
			<sys:String x:Key="strPanel">Hello, Panel world!</sys:String>
		</DockPanel.Resources>

		<WrapPanel DockPanel.Dock="Top" HorizontalAlignment="Center" Margin="10">
			<Button Name="btnClickMe" Click="btnClickMe_Click">Click me!</Button>
		</WrapPanel>

		<ListBox Name="lbResult" />
	</DockPanel>
</Window>

CodeBehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPF_Resource
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnClickMe_Click(object sender, RoutedEventArgs e)
        {
            lbResult.Items.Add(pnlMain.FindResource("strPanel").ToString());
            lbResult.Items.Add(this.FindResource("strWindow").ToString());
            lbResult.Items.Add(Application.Current.FindResource("strApp").ToString());
        }
    }
}

결과

버튼을 누르면 CodeBehind에서 정의한 이벤트 함수가 실행된다.
FindResource(string str)메서드를 통해 리소스를 찾으면 object형식으로 반환한다.

profile
Dreams Come True

0개의 댓글