WPF: Resources

Resource를 활용하자!!

WPF에서는 데이터를 리소스 형태로 저장하는 것이 가능하다.
이 데이터들은 실제 데이터일 수도 있고, 컨트롤들의 계층 구조일 수도 있다.
이렇게 저장된 리소스들은 템플릿등을 구성할 때 자주 사용된다.

간단한 예제를 한번 보자. (feat. Hello world!!)

MyWPFApp.xaml
<Window x:Class="WpfApp1.MyWPFApp"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        ResizeMode="CanResizeWithGrip">
    <Window.Resources>
        <sys:String x:Key="sTextResource"> Hello, world!!</sys:String>
    </Window.Resources>
    <StackPanel Margin="10">
        <TextBlock Text="{StaticResource sTextResource}" FontSize="72" />
    </StackPanel>
</Window>

윈도의 리소스로 'Hello, world!!'라는 스트링을 하나 추가한 다음, 텍스트 블록으로 이 리소스를 불러왔다.
이 때 x:Key 속성이 사용되고, 키를 이용하여 리소스를 참조할 수 있었다.

리소스는 변수의 선언 위치에 따라 사용 가능한 영역이 달라지듯, 저장되는 위치에 따라 참조할 수 있는 범위가 달라진다.
다시 말해, 특정 컨트롤에서 저장된 리소스는 그 컨트롤 안에서만 활용이 가능하고,
App.xaml 내부에 저장되는 리소스는 프로젝트의 모든 윈도우와 컨트롤에서 참조가 가능하다.

다음의 예를 살펴보자.

App.xaml
<Application x:Class="WpfApp1.App"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MyWPFApp.xaml">
    <Application.Resources>
        <sys:String x:Key="sAppResource"> I'm in the App!!</sys:String>
    </Application.Resources>
</Application>

MyWPFApp.xaml
<Window x:Class="WpfApp1.MyWPFApp"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="220" Width="295"
        ResizeMode="CanResizeWithGrip">
    <Window.Resources>
        <sys:String x:Key="sWindowResource">I'm in the Window!!</sys:String>
    </Window.Resources>
    <Grid Margin="10" Name="grdMain">
        <Grid.Resources>
            <sys:String x:Key="sGridResource">I'm in the Grid!!</sys:String>
        </Grid.Resources>
       
        <Button Content="App&#10;Resource" Name="btnApp" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Height="34" FontWeight="Bold" Click="btnApp_Click"/>
        <Button Content="Window&#10;Resource" Name="btnWindow" HorizontalAlignment="Left" Margin="95,10,0,0" VerticalAlignment="Top" Width="75" Height="34" FontWeight="Bold" Click="btnWindow_Click"/>
        <Button Content="Grid&#10;Resource" Name="btnGrid" HorizontalAlignment="Left" Margin="180,10,0,0" VerticalAlignment="Top" Width="75" Height="34" FontWeight="Bold" Click="btnGrid_Click"/>
        <ListBox Name="lbResult" HorizontalAlignment="Left" Height="100" Margin="10,54,0,0" VerticalAlignment="Top" Width="245"/>
    </Grid>
</Window>

MyWPFApp.xaml.cs
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 WpfApp1
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MyWPFApp: Window
    {
        public MyWPFApp()
        {
            InitializeComponent();
        }
        private void btnApp_Click(object sender, RoutedEventArgs e)
        {
            this.lbResult.Items.Add(Application.Current.FindResource("sAppResource").ToString());
        }
        private void btnWindow_Click(object sender, RoutedEventArgs e)
        {
            this.lbResult.Items.Add(this.FindResource("sWindowResource").ToString());
        }
        private void btnGrid_Click(object sender, RoutedEventArgs e)
        {
            this.lbResult.Items.Add(this.grdMain.FindResource("sGridResource").ToString());
        }
    }
}



예제에서 보는 것 처럼 리소스는 프로젝트 전체에 걸쳐서 저장할 수 있다.
이렇게 저장된 리소스들은 비하인드 코드에서도 FindResource() 메소드를 통해 참조할 수 있다.
단, 각기 다른 계층에 저장된 리소스를 참조하는 방법에 대해서 눈여겨보자. ㅎㅎ

Share:
spacer

댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.