본문 바로가기

C# WPF

C# WPF 팁 - 버튼 디자인

C# WPF에서 버튼의 스타일을 바꾸는 간단한 팁을 알려드리겠습니다.

원래 기본적으로 버튼을 생성 시 회색빛 디자인의 버튼이 생성되지만


이 디자인이 마음에 들지 않는 경우 사용자가 직접 버튼 스타일을 만들어 줘야 합니다.

버튼스타일은 해당 윈도우의 xaml창에서 코딩해줘도 되지만

더 좋은 방법은 msdn에 나와 있는대로 App.xaml파일에서 스타일을 코딩해주면 좀 더 깔끔한 코딩이 될 것 같습니다.


<Application x:Class="WidthHeightToInch.App"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             StartupUri="MainWindow.xaml">

    <Application.Resources>


        <Style TargetType="Button" x:Key="GreenButton" >

            <Setter Property="Background" Value="#FF99DD99"></Setter>

        </Style>


    </Application.Resources>

</Application>


위에서 간단하게 짠 스타일의 의미는 
TargetType="Button" -> "Button"을 스타일이 적용될 목표로, 
x:Key="GreenButton" -> 스타일 식별키는 GreenButton으로, 
Property="Background"-> Background(배경색) 속성을 
Value="#FF99DD99"-> "#FF99DD99"색으로 하겠다는 의미입니다.

이와 같이 스타일을 정의해준 뒤,

버튼을 그려줄 윈도우의 xaml파일을 열어 툴박스에서 Button을 드래그 드롭으로 그려준 뒤 xaml 코드를 아래와 같이

버튼의 스타일을 지정해줍니다.


 <Button Content="Button" Style="{StaticResource GreenButton}" HorizontalAlignment="Left" Margin="105,64,0,0" VerticalAlignment="Top" Height="53" Width="112" />


결과는 다음과 같이 스타일 정의대로 배경색이 "#FF99DD99"인 버튼이 생성됨을 알 수 있습니다.

이와 같이 여러 스타일을 만들어 놓으신 후 필요할때 스타일 식별키를 이용하여 버튼에 손쉽게 적용하면 좀 더 멋진 디자인의 프로그램을 만들 수 있을 것 같습니다.


간단히 응용하자면, 

버튼 테두리 모양도 변경할 수 있는데 뾰족한 사각형의 버튼을 만들어 보겠습니다.


<Application x:Class="WidthHeightToInch.App"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             StartupUri="MainWindow.xaml">

    <Application.Resources>


       <ControlTemplate TargetType="Button" x:Key="square">

            <Border Background="#FF99DD99">

                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>

            </Border>

        </ControlTemplate>

        

        <Style TargetType="Button" x:Key="GreenButton" >

            <Setter Property="Template" Value="{StaticResource square}"/>

        </Style>


        


    </Application.Resources>

</Application>



위와 같이 먼저 style에서 

Property="Template" -> 템플릿 속성의 

<Setter.Value> -> 값을 square라는 템플릿으로 설정


이렇게 코딩한 뒤 스타일 정의 앞에 다음과 같이 컨트롤템플릿을 정의해야 합니다.

<ControlTemplate TargetType="Button" x:Key="square">   -> Button 컨트롤을 목표로, 컨트롤 템플릿 식별키는 square로,

<Border Background="#FF99DD99">       -> Border로 하고 배경색은 "#FF99DD99"색으로,

<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>   ->버튼내용은 가로세로 중앙정렬

</Border>

 </ControlTemplate>


이렇게 설정한다면 결과물은 다음과 같습니다.


세밀하게 사각형의 끝지점을 둥글게 다듬고 싶다면 CornerRadius를 이용하여 

<ControlTemplate TargetType="Button" x:Key="square">

            <Border Background="#FF99DD99" CornerRadius="5" >

                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>

            </Border>

</ControlTemplate>


다음과 같이 CornerRadius의 수치에 따라 사각형 모서리가 둥글게 바뀜을 확인하실 수 있습니다.