본문 바로가기

Programing (프로그래밍)/WPF & C# (C Sharp)

WPF & C# - 스타일적용하기 방법 예제 ( Style )

728x90
반응형


 WPF & C# - 스타일적용하기 방법 예제 ( Style )



testStyle.zip




01. 리소스 사전을 추가 한다.

 > 해당프로젝트 > 마우스 우클릭 > 추가 > 리소스 사전 > Dictionary1.xaml 생성 및 추가


Dictionary1.xaml



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<Style TargetType="Button" x:Key="btnAstyle">
    <Setter Property="Width" Value="100"/>
    <Setter Property="Height" Value="50"/>
    <Setter Property="Background" Value="Aqua"/>
    <Setter Property="Content" Value="A스타일"/>
 
</Style>
 
<Style TargetType="Button" x:Key="btnBstyle">
    <Setter Property="Width" Value="100"/>
    <Setter Property="Height" Value="50"/>
    <Setter Property="Background" Value="Green"/>
    <Setter Property="Content" Value="B스타일"/>
</Style>
 
<Style TargetType="Button" x:Key="btnCstyle">
    <Setter Property="Width" Value="100"/>
    <Setter Property="Height" Value="50"/>
    <Setter Property="Background" Value="DarkGray"/>
    <Setter Property="Content" Value="C스타일"/>
</Style>
cs



02. App.xaml 에서 리소스파일을 불러온다.


App.xaml



1
2
3
4
5
6
7
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
cs



03. 해당 프로젝트에 적용한다.


MainWindow.xaml



1
2
3
4
<StackPanel x:Name="stp" Orientation="Vertical">
    <Button Style="{DynamicResource btnAstyle}"/>
    <Button Style="{DynamicResource btnBstyle}"/>
</StackPanel>
cs



04. 만약 코드로 적용할 시에는 아래와 같이 적용한다.


MainWindow.xaml.cs ( 스타일이 App.xaml 에 있는 경우 )



1
2
3
4
5
6
7
8
Button btnC = new Button();
btnC.Style = Application.Current.Resources["btnCstyle"as Style;
 
Button btnA = new Button();
btnA.Style = Application.Current.Resources["btnAstyle"as Style;
 
stp.Children.Add(btnC);
stp.Children.Add(btnA);
cs



MainWindow.xaml.cs ( 스타일이 MainWindow.xaml 에 있는 경우 )



1
2
3
4
5
6
7
8
Button btnC = new Button();
btnC.Style = Resources["btnCstyle"as Style;
 
Button btnA = new Button();
btnC.Style = Resources["btnAstyle"as Style;
 
stp.Children.Add(btnC);
stp.Children.Add(btnA);
cs


728x90
반응형