레이블이 C#인 게시물을 표시합니다. 모든 게시물 표시
레이블이 C#인 게시물을 표시합니다. 모든 게시물 표시

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() 메소드를 통해 참조할 수 있다.
단, 각기 다른 계층에 저장된 리소스를 참조하는 방법에 대해서 눈여겨보자. ㅎㅎ

spacer

WPF: Window Class Properties


WPF Application의 가장 밑바탕이 되는 Window 클래스의 속성들을 살펴보자.

주요 Window 속성

Icon: 윈도우의 아이콘을 정의

ResizeMode: 사용자가 윈도우 App의 크기를 조정할 수 있는지에 대한 속성으로,
기본 값은 "CanResize"이고, 다른 윈도우처럼 크기 조정이 가능하다.

ShowInTaskbar: 윈도우 App이 윈도우의 Task Bar에 보여질 것인지를 나타내는 속성으로,
기본 값은 "True"이고, "False"로 설정 시 Task Bar에 표시되지 않는다.

SizeToConent: 내용에 따라 윈도우 App의 크기를 자동으로 조정할지의 여부를 나타내는 속성으로,
기본 값은 "Manual"이고 자동으로 재조정하지 않는다는 의미이다.
사용 가능한 옵션으로 "Width", "Height", "WidthAndHeight'가 있다.

Topmost: 윈도우 App이 다른 창들보다 위에 위치할 것인지를 나타내는 속성으로,
기본 값은 "False"이다.

WindowStartupLocation: 윈도우 App의 초기 위치에 대한 속성으로, 기본 값은 "Manual"이고,
"Top", "Left" 속성에 따라 초기 위치가 결정된다. 그 외 "CenterOwner"는 윈도우 App의 중앙에 위치시키고,
"CenterScreen"은 화면의 중앙에 위치시킨다.

WindowState: 초기 윈도우 App 상태에 대한 속성으로, "Normal", "Maximized", "Minimized"를 설정할 수 있다.
기본 값은 "Normal"이다.

 
spacer