본문 바로가기
Windows/C#/WPF

리소스 & ControlTemplate

by hirudev 2021. 5. 8.
    <Window.Resources>
        <SolidColorBrush x:Key="SolidBrushTest" Color="Blue"/>
    </Window.Resources>
    <Canvas>
        <Border Background="{StaticResource SolidBrushTest}" Width="100" Height="100" Canvas.Top="10" x:Name="staticBorder" />
        <Border Background="{DynamicResource SolidBrushTest}" Width="100" Height="100" Canvas.Bottom="10" x:Name="dynamicBorder" />
    </Canvas>

 

this.Resources["SolidBrushTest"] = new SolidColorBrush(Color.FromRgb(0xFF, 0, 0));

 

 

solidbrush (파란색) 의 키 값을 SolidBrushTest 으로 두고

 

하나는 StaticResource 다른 하나는 DynamicResource 로 두었다.

 

다음 C# 소스 창에는 리소스 SolidBrushTest 의 값을 255, 0, 0 으로 둠으로써 기존의 파란색을 빨간색으로 바꾸었다.

 

 

결과는 StaticResource 는 기본으로 설정된 파란색으로 되어있지만 DynamicResource 는 빨간색으로 변경되었다.

 

var brush = (SolidColorBrush)this.FindResource("SolidBrushTest"); 
this.border.Background = brush; 

 

리소스를 C#으로 불러오고자 할 때는 위와 같이 가능하다.

 


ResourceDictionary

 

<!-- ResourceDictionary.xaml -->
    <ControlTemplate x:Key="TestTemplate" TargetType="{x:Type UserControl}" >
        <Grid ShowGridLines="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <Button Grid.Column="0" Grid.Row="0" Content="Left Top" />
        </Grid>
    </ControlTemplate>

 

<!-- MainWindow.xaml -->
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ResourceDictionary Source="ResourceDictionary.xaml" />
    </Window.Resources>
    <UserControl Template="{StaticResource TestTemplate}" />
</Window>

 

위와 같이 리소스를 별도로 관리하면서 접근이 가능하다.

 

 

 

'Windows > C#/WPF' 카테고리의 다른 글

데이터 바인딩 2  (0) 2021.05.11
데이터 바인딩 1  (0) 2021.05.09
스타일  (0) 2021.05.08
애니메이션  (0) 2021.05.08
이벤트 핸들러  (0) 2021.05.07

댓글