본문 바로가기
C#/WPF

[WPF] 컨트롤에 동적으로 스타일 적용

by 민방 2023. 5. 15.

 WPF를 사용하다가 xaml 파일에서가 아닌 cs 파일에서 동적으로 컨트롤을 추가하는 경우가 있다. 해당 경우에 미리 등록해놓은 스타일을 불러올 수 있는 방법이다.

xaml 파일 구조

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:gif="http://wpfanimatedgif.codeplex.com">
                    
<!-- 사용할 버튼 스타일 정의 -->
<Style TargetType="Button" x:Key="BlackBtn">
        <Setter Property="Background" Value="White"/>
        <Setter Property="BorderBrush" Value="#38404A"/>
        <Setter Property="BorderThickness" Value="1.5"/>
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="FontSize" Value="12"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}" 
                            BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="3"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#D9DFE8" TargetName="Border" />
                            <Setter Property="Cursor" Value="Hand"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" Value="0.5" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    </ResourceDictionary>

 

cs 파일 구조

using System.Windows;
using System.Windows.Controls;

//버튼 스타일을 가져올 xaml파일 지정
ResourceDictionary resourceDictionary = new ResourceDictionary
{
	Source = new Uri("/Resources/Style.xaml", UriKind.RelativeOrAbsolute)
};

//컨트롤 생성
private Button CreateButton()
{
	//원하는 버튼 스타일의 이름을 통해 받아옴
	var buttonStyle = resourceDictionary["BlackBtn"] as Style;

	Button NewButton = new Button();
    NewButton.Style = buttonStyle;
    return NewButton;
}

 

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

[WPF] WPF에 Winform 컨트롤 불러오는 방법  (0) 2023.09.06
[WPF] XAML 디자인 창 컨트롤 숨기기  (0) 2023.04.07
[WPF] ListView 갱신하는 방법  (0) 2023.04.06

댓글