[PYTHON/LANGCHAIN] RunnableSequence 클래스 : batch 메소드에서 config 인자를 사용해 동시 작업 수 설정하기
■ RunnableSequence 클래스의 batch 메소드에서 config 인자를 사용해 동시 작업 수를 설정하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다.
■ RunnableSequence 클래스의 batch 메소드에서 config 인자를 사용해 동시 작업 수를 설정하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다.
■ PromptTemplate 클래스의 from_template 정적 메소드를 사용해 PromptTemplate 객체를 만드는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶ main.py
■ RunnableSequence 클래스의 invoke 메소드를 사용해 LCEL 체인을 실행하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from dotenv import load_dotenv from langchain_core.prompts import PromptTemplate from langchain_openai import ChatOpenAI load_dotenv() templateString = "{country}의 수도는 어디입니까?" promptTemplate = PromptTemplate.from_template(templateString) chatOpenAI = ChatOpenAI( model_name = "gpt-4o-mini", # 모델명 max_tokens = 2048, # 최대 토큰 수 temperature = 0.1, # 창의성 (0.0 ~ 2.0) ) runnableSequence = promptTemplate | chatOpenAI responseAIMessage = runnableSequence.invoke({"country" : "미국"}) print(responseAIMessage.content) """ 미국의 수도는 워싱턴 D.C.입니다. """ |
■ get_query_constructor_prompt 함수를 사용해 FewShotPromptTemplate 객체를 만드는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
from langchain.chains.query_constructor.base import AttributeInfo attributeInfoList = [ AttributeInfo( name = "genre", description = "The genre of the movie. One of ['science fiction', 'comedy', 'drama', 'thriller', 'romance', 'action', 'animated']", type = "string" ), AttributeInfo( name = "year", description = "The year the movie was released", type = "integer" ), AttributeInfo( name = "director", description = "The name of the movie director", type = "string" ), AttributeInfo( name = "rating", description = "A 1-10 rating for the movie", type = "float" ) ] documentContentDescription = "Brief summary of a movie" fewShotPromptTemplate = get_query_constructor_prompt( documentContentDescription, attributeInfoList ) |
※ pip install langchain 명령을 실행했다.
■ OpenAI 클래스에서 CommaSeparatedListOutputParser 객체를 사용하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from dotenv import load_dotenv from langchain_core.output_parsers import CommaSeparatedListOutputParser from langchain_core.prompts import PromptTemplate from langchain_openai import OpenAI load_dotenv() commaSeparatedListOutputParser = CommaSeparatedListOutputParser() formatInstructionString = commaSeparatedListOutputParser.get_format_instructions() promptTemplate = PromptTemplate( template = "{주제} 5개를 추천해주세요.\n{format_instructions}", input_variables = ["주제"], partial_variables = {"format_instructions" : formatInstructionString} ) openAI = OpenAI(temperature = 1) runnableSequence = promptTemplate | openAI | commaSeparatedListOutputParser responseList = runnableSequence.invoke({"주제" : "영화"}) for response in responseList: print(response) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
annotated-types==0.7.0 anyio==4.4.0 certifi==2024.8.30 charset-normalizer==3.3.2 colorama==0.4.6 distro==1.9.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.8 jiter==0.5.0 jsonpatch==1.33 jsonpointer==3.0.0 langchain-core==0.2.39 langchain-openai==0.1.23 langsmith==0.1.117 openai==1.44.1 orjson==3.10.7 packaging==24.1 pydantic==2.9.1 pydantic_core==2.23.3 python-dotenv==1.0.1 PyYAML==6.0.2 regex==2024.7.24 requests==2.32.3 sniffio==1.3.1 tenacity==8.5.0 tiktoken==0.7.0 tqdm==4.66.5 typing_extensions==4.12.2 urllib3==2.2.2 |
■ ChatOpenAI 클래스에서 SemanticSimilarityExampleSelector 객체를 사용해 채팅하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
from dotenv import load_dotenv from langchain_openai import OpenAIEmbeddings from langchain_chroma import Chroma from langchain_core.example_selectors import SemanticSimilarityExampleSelector from langchain_core.prompts import PromptTemplate from langchain_core.prompts.few_shot import FewShotPromptTemplate from langchain_openai import ChatOpenAI load_dotenv() exampleList = [ {"input" : "행복" , "output" : "슬픔" }, {"input" : "흥미" , "output" : "지루" }, {"input" : "불안" , "output" : "안정" }, {"input" : "긴 기차", "output" : "짧은 기차"}, {"input" : "큰 공" , "output" : "작은 공" } ] openAIEmbeddings = OpenAIEmbeddings() semanticSimilarityExampleSelector = SemanticSimilarityExampleSelector.from_examples( exampleList, openAIEmbeddings, Chroma, k = 1 ) examplePromptTemplate = PromptTemplate( input_variables = ["input", "output"], template = "Input : {input}\nOutput : {output}" ) fewShotPromptTemplate = FewShotPromptTemplate( example_selector = semanticSimilarityExampleSelector, example_prompt = examplePromptTemplate, prefix = "주어진 입력에 대해 반대의 의미를 가진 단어를 출력해주세요.", suffix = "Input : {단어}\nOutput : ", input_variables = ["단어"] ) chatOpenAI = ChatOpenAI(model_name = "gpt-4o-mini") runnableSequence = fewShotPromptTemplate | chatOpenAI responseAIMessage = runnableSequence.invoke({"단어" : "무서운"}) print(responseAIMessage.content) |
▶ requirements.txt
■ FewShotPromptTemplate 클래스의 생성자에서 example_selector 인자를 사용해 SemanticSimilarityExampleSelector 객체를 설정하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶ main.py
■ Button 클래스를 사용해 중단 버튼을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:StopButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="CornerRadius" Value="5" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="#003e92" /> <Setter Property="Background" Value="#fcfcfc" /> <Setter Property="Foreground" Value="Black" /> <Setter Property="Padding" Value="10" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:StopButton}"> <Border Name="PART_RootBorder" Padding="{TemplateBinding Padding}" CornerRadius="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CornerRadius}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal"> <Viewbox Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IconWidth}" Height="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IconHeight}"> <Path Name="PART_IconPath" Fill="#003e92" Stretch="Uniform" Data="M 0 0 H 20 V 20 H 0 Z" /> </Viewbox> <TextBlock Name="PART_ContentTextBlock" VerticalAlignment="Center" Margin="8 0 0 0" FontSize="14" Text="{TemplateBinding Content}" /> </StackPanel> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="PART_RootBorder" Property="Background" Value="#f0f0f0" /> <Setter TargetName="PART_IconPath" Property="Fill" Value="#0050b8" /> <Setter TargetName="PART_ContentTextBlock" Property="Foreground" Value="#0050b8" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="PART_RootBorder" Property="Background" Value="#e0e0e0" /> <Setter TargetName="PART_IconPath" Property="Fill" Value="#002a66" /> <Setter TargetName="PART_ContentTextBlock" Property="Foreground" Value="#002a66" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <local:StopButton HorizontalAlignment="Center" VerticalAlignment="Center" Padding="10" Content="Stop" /> </Window> |
▶ StopButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
using System.Windows; using System.Windows.Controls; namespace TestProject; /// <summary> /// 중단 버튼 /// </summary> public class StopButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 속성 - CornerRadiusProperty /// <summary> /// 코너 반경 속성 /// </summary> public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register ( "CornerRadius", typeof(CornerRadius), typeof(StopButton), new PropertyMetadata(new CornerRadius(5)) ); #endregion #region 아이콘 너비 속성 - IconWidthProperty /// <summary> /// 아이콘 너비 속성 /// </summary> public static readonly DependencyProperty IconWidthProperty = DependencyProperty.Register ( "IconWidth", typeof(double), typeof(StopButton), new PropertyMetadata(14.0) ); #endregion #region 아이콘 높이 속성 - IconHeightProperty /// <summary> /// 아이콘 높이 속성 /// </summary> public static readonly DependencyProperty IconHeightProperty = DependencyProperty.Register ( "IconHeight", typeof(double), typeof(StopButton), new PropertyMetadata(14.0) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 - CornerRadius /// <summary> /// 코너 반경 /// </summary> public CornerRadius CornerRadius { get => (CornerRadius)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } #endregion #region 아이콘 너비 - IconWidth /// <summary> /// 아이콘 너비 /// </summary> public double IconWidth { get => (double)GetValue(IconWidthProperty); set => SetValue(IconWidthProperty, value); } #endregion #region 아이콘 높이 - IconHeight /// <summary> /// 아이콘 높이 /// </summary> public double IconHeight { get => (double)GetValue(IconHeightProperty); set => SetValue(IconHeightProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - StopButton() /// <summary> /// 생성자 /// </summary> static StopButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(StopButton), new FrameworkPropertyMetadata(typeof(StopButton))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - StopButton /// <summary> /// 생성자 /// </summary> public StopButton() : base() { Content = "Stop"; } #endregion } |
TestProject.zip
■ Control 클래스를 사용해 이미지 회전 목마 컨트롤을 만드는 방법을 보여준다. ▶ ArrowButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 화살표 버튼 /// </summary> public class ArrowButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 스트로크 두께 속성 - BackgroundEllipseStrokeThicknessProperty /// <summary> /// 배경 원 두께 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeThicknessProperty = DependencyProperty.Register ( "BackgroundEllipseStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(0)) ); #endregion #region 배경 원 스트로크 속성 - BackgroundEllipseStrokeProperty /// <summary> /// 배경 원 패스 데이터 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeProperty = DependencyProperty.Register ( "BackgroundEllipseStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 배경 원 채우기 속성 - BackgroundEllipseFillProperty /// <summary> /// 배경 원 채우기 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseFillProperty = DependencyProperty.Register ( "BackgroundEllipseFill", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 화살표 크기 속성 - ArrowSizeProperty /// <summary> /// 화살표 크기 속성 /// </summary> public static readonly DependencyProperty ArrowSizeProperty = DependencyProperty.Register ( "ArrowSize", typeof(double), typeof(ArrowButton), new PropertyMetadata(20.0) ); #endregion #region 화살표 방향 속성 - ArrowDirectionProperty /// <summary> /// 화살표 방향 속성 /// </summary> public static readonly DependencyProperty ArrowDirectionProperty = DependencyProperty.Register ( "ArrowDirection", typeof(ArrowDirection), typeof(ArrowButton), new PropertyMetadata(ArrowDirection.Left, DirectionPropertyChangedCallback) ); #endregion #region 화살표 스트로크 두께 속성 - ArrowStrokeThicknessProperty /// <summary> /// 화살표 두께 /// </summary> public static readonly DependencyProperty ArrowStrokeThicknessProperty = DependencyProperty.Register ( "ArrowStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(1)) ); #endregion #region 화살표 스트로크 속성 - ArrowStrokeProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowStrokeProperty = DependencyProperty.Register ( "ArrowStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Black) ); #endregion #region 왼쪽 화살표 패스 데이터 속성 - LeftArrowPathDataProperty /// <summary> /// 왼쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty LeftArrowPathDataProperty = DependencyProperty.Register ( "LeftArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 오른쪽 화살표 패스 데이터 속성 - RightArrowPathDataProperty /// <summary> /// 오른쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty RightArrowPathDataProperty = DependencyProperty.Register ( "RightArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 5 10 L 15 10 M 15 10 L 10 5 M 15 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 화살표 패스 데이터 속성 - ArrowPathDataProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowPathDataProperty = DependencyProperty.Register ( "ArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15") ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 채우기 - BackgroundEllipseFill /// <summary> /// 배경 원 채우기 /// </summary> public Brush BackgroundEllipseFill { get => (Brush)GetValue(BackgroundEllipseFillProperty); set => SetValue(BackgroundEllipseFillProperty, value); } #endregion #region 배경 원 스트로크 두께 - BackgroundEllipseStrokeThickness /// <summary> /// 배경 원 스트로크 두께 /// </summary> public Thickness BackgroundEllipseStrokeThickness { get => (Thickness)GetValue(BackgroundEllipseStrokeThicknessProperty); set => SetValue(BackgroundEllipseStrokeThicknessProperty, value); } #endregion #region 배경 원 스트로크 - BackgroundEllipseStroke /// <summary> /// 배경 원 스트로크 /// </summary> public Brush BackgroundEllipseStroke { get => (Brush)GetValue(BackgroundEllipseStrokeProperty); set => SetValue(BackgroundEllipseStrokeProperty, value); } #endregion #region 화살표 크기 - ArrowSize /// <summary> /// 화살표 크기 /// </summary> public double ArrowSize { get => (double)GetValue(ArrowSizeProperty); set => SetValue(ArrowSizeProperty, value); } #endregion #region 화살표 방향 - ArrowDirection /// <summary> /// 화살표 방향 /// </summary> public ArrowDirection ArrowDirection { get => (ArrowDirection)GetValue(ArrowDirectionProperty); set => SetValue(ArrowDirectionProperty, value); } #endregion #region 화살표 스트로크 두께 - ArrowStrokeThickness /// <summary> /// 화살표 스트로크 두께 /// </summary> public Thickness ArrowStrokeThickness { get => (Thickness)GetValue(ArrowStrokeThicknessProperty); set => SetValue(ArrowStrokeThicknessProperty, value); } #endregion #region 화살표 스트로크 - ArrowStroke /// <summary> /// 화살표 스트로크 /// </summary> public Brush ArrowStroke { get => (Brush)GetValue(ArrowStrokeProperty); set => SetValue(ArrowStrokeProperty, value); } #endregion #region 왼쪽 화살표 패스 데이터 - LeftArrowPathData /// <summary> /// 왼쪽 화살표 패스 데이터 /// </summary> public string LeftArrowPathData { get => (string)GetValue(LeftArrowPathDataProperty); set => SetValue(LeftArrowPathDataProperty, value); } #endregion #region 오른쪽 화살표 패스 데이터 - RightArrowPathData /// <summary> /// 오른쪽 화살표 패스 데이터 /// </summary> public string RightArrowPathData { get => (string)GetValue(RightArrowPathDataProperty); set => SetValue(RightArrowPathDataProperty, value); } #endregion #region 화살표 패스 데이터 - ArrowPathData /// <summary> /// 화살표 패스 데이터 /// </summary> public string ArrowPathData { get => (string)GetValue(ArrowPathDataProperty); private set => SetValue(ArrowPathDataProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ArrowButton() /// <summary> /// 생성자 /// </summary> static ArrowButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ArrowButton), new FrameworkPropertyMetadata(typeof(ArrowButton))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 방향 속성 변경시 콜백 처리하기 - DirectionPropertyChangedCallback(d, e) /// <summary> /// 방향 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void DirectionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion #region 화살표 패스 데이터 속성 변경시 콜백 처리하기 - ArrowPathDataPropertyChangedCallback(d, e) /// <summary> /// 화살표 패스 데이터 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ArrowPathDataPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region 화살표 패스 데이터 업데이트하기 - UpdateArrowPathData() /// <summary> /// 화살표 패스 데이터 업데이트하기 /// </summary> private void UpdateArrowPathData() { ArrowPathData = ArrowDirection == ArrowDirection.Left ? LeftArrowPathData : RightArrowPathData; } #endregion } |
▶ ArrowDirection.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
namespace TestProject; /// <summary> /// 화살표 방향 /// </summary> public enum ArrowDirection { Left, Right } |
▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ArrowButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ArrowButton}"> <Grid Name="grid"> <Ellipse Name="backgroundEllipse" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStroke}" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseFill}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ArrowSize}" Height="{TemplateBinding ArrowSize}" Margin="{TemplateBinding Padding}"> <Canvas Width="20" Height="20"> <Path Name="arrowPath" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStroke}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Data="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowPathData}" /> </Canvas> </Viewbox> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#e0e0e0" /> <Setter TargetName="arrowPath" Property="Stroke" Value="Black" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#bdbdbd" /> <Setter TargetName="grid" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="1" Y="1" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Width" Value="32" /> <Setter Property="Height" Value="32" /> <Setter Property="ArrowSize" Value="20" /> </Style> <Style TargetType="{x:Type local:ImageCarousel}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ImageCarousel}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="10" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="10" /> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <local:ArrowButton x:Name="PART_LeftArrowButton" Grid.Column="0" Width="32" Height="32" ArrowDirection="Left" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="DarkGray" /> <Canvas Name="PART_ItemCanvas" Grid.Column="2" ClipToBounds="True" /> <local:ArrowButton x:Name="PART_RightArrowButton" Grid.Column="4" Width="32" Height="32" ArrowDirection="Right" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="DarkGray" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ ImageCarousel.cs
■ Button 클래스를 사용해 이미지 버튼을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ImageButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ImageButton}"> <Border Name="PART_Border" Background="Transparent"> <Grid> <Image Name="PART_IconImage" HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ImageWidth}" Height="{TemplateBinding ImageHeight}" Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=EnabledImageSource}" /> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="PART_IconImage" Property="RenderTransform"> <Setter.Value> <ScaleTransform ScaleX="0.9" ScaleY="0.9" /> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="PART_IconImage" Property="Source" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisabledImageSource}" /> <Setter Property="Opacity" Value="0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ ImageButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 이미지 버튼 /// </summary> public class ImageButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Statc //////////////////////////////////////////////////////////////////////////////// Statc #region 이미지 너비 속성 - ImageWidthProperty /// <summary> /// 이미지 너비 속성 /// </summary> public static readonly DependencyProperty ImageWidthProperty = DependencyProperty.Register ( "ImageWidth", typeof(double), typeof(ImageButton), new PropertyMetadata(32.0) ); #endregion #region 이미지 높이 속성 - ImageHeightProperty /// <summary> /// 이미지 높이 속성 /// </summary> public static readonly DependencyProperty ImageHeightProperty = DependencyProperty.Register ( "ImageHeight", typeof(double), typeof(ImageButton), new PropertyMetadata(32.0) ); #endregion #region 이용 가능 이미지 소스 속성 - EnabledImageSourceProperty /// <summary> /// 이용 가능 이미지 소스 속성 /// </summary> public static readonly DependencyProperty EnabledImageSourceProperty = DependencyProperty.Register ( "EnabledImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null) ); #endregion #region 이용 불가 이미지 소스 속성 - DisabledImageSourceProperty /// <summary> /// 이용 불가 이미지 소스 속성 /// </summary> public static readonly DependencyProperty DisabledImageSourceProperty = DependencyProperty.Register ( "DisabledImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 이미지 너비 - ImageWidth /// <summary> /// 이미지 너비 /// </summary> public double ImageWidth { get => (double)GetValue(ImageWidthProperty); set => SetValue(ImageWidthProperty, value); } #endregion #region 이미지 높이 - ImageHeight /// <summary> /// 이미지 높이 /// </summary> public double ImageHeight { get => (double)GetValue(ImageHeightProperty); set => SetValue(ImageHeightProperty, value); } #endregion #region 이용 가능 이미지 소스 - EnabledImageSource /// <summary> /// 이용 가능 이미지 소스 /// </summary> public ImageSource EnabledImageSource { get => (ImageSource)GetValue(EnabledImageSourceProperty); set => SetValue(EnabledImageSourceProperty, value); } #endregion #region 이용 불가 이미지 소스 - DisabledImageSource /// <summary> /// 이용 불가 이미지 소스 /// </summary> public ImageSource DisabledImageSource { get => (ImageSource)GetValue(DisabledImageSourceProperty); set => SetValue(DisabledImageSourceProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Statc #region 생성자 - ImageButton /// <summary> /// 생성자 /// </summary> static ImageButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton))); } #endregion } |
▶ MainApplication.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <local:ImageButton x:Name="imageButton1" Width="40" Height="40" ImageWidth="40" ImageHeight="40" EnabledImageSource="IMAGE/new_chat.png" DisabledImageSource="IMAGE/new_chat_gray.png" /> <local:ImageButton x:Name="imageButton2" Margin="0 20 0 0" Width="20" Height="20" ImageWidth="18" ImageHeight="18" EnabledImageSource="IMAGE/send.png" DisabledImageSource="IMAGE/send_gray.png" /> <Button Name="toggleButton" Margin="0 30 0 0" Padding="10" Content="IsEnabled 속성 토글" /> </StackPanel> </Window> |
▶
■ Control 클래스를 사용해 이미지 회전 목마 컨트롤을 만드는 방법을 보여준다. ▶ ArrowButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 화살표 버튼 /// </summary> public class ArrowButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 스트로크 두께 속성 - BackgroundEllipseStrokeThicknessProperty /// <summary> /// 배경 원 두께 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeThicknessProperty = DependencyProperty.Register ( "BackgroundEllipseStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(0)) ); #endregion #region 배경 원 스트로크 속성 - BackgroundEllipseStrokeProperty /// <summary> /// 배경 원 패스 데이터 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeProperty = DependencyProperty.Register ( "BackgroundEllipseStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 배경 원 채우기 속성 - BackgroundEllipseFillProperty /// <summary> /// 배경 원 채우기 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseFillProperty = DependencyProperty.Register ( "BackgroundEllipseFill", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 화살표 크기 속성 - ArrowSizeProperty /// <summary> /// 화살표 크기 속성 /// </summary> public static readonly DependencyProperty ArrowSizeProperty = DependencyProperty.Register ( "ArrowSize", typeof(double), typeof(ArrowButton), new PropertyMetadata(20.0) ); #endregion #region 화살표 방향 속성 - ArrowDirectionProperty /// <summary> /// 화살표 방향 속성 /// </summary> public static readonly DependencyProperty ArrowDirectionProperty = DependencyProperty.Register ( "ArrowDirection", typeof(ArrowDirection), typeof(ArrowButton), new PropertyMetadata(ArrowDirection.Left, DirectionPropertyChangedCallback) ); #endregion #region 화살표 스트로크 두께 속성 - ArrowStrokeThicknessProperty /// <summary> /// 화살표 두께 /// </summary> public static readonly DependencyProperty ArrowStrokeThicknessProperty = DependencyProperty.Register ( "ArrowStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(1)) ); #endregion #region 화살표 스트로크 속성 - ArrowStrokeProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowStrokeProperty = DependencyProperty.Register ( "ArrowStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Black) ); #endregion #region 왼쪽 화살표 패스 데이터 속성 - LeftArrowPathDataProperty /// <summary> /// 왼쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty LeftArrowPathDataProperty = DependencyProperty.Register ( "LeftArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 오른쪽 화살표 패스 데이터 속성 - RightArrowPathDataProperty /// <summary> /// 오른쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty RightArrowPathDataProperty = DependencyProperty.Register ( "RightArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 5 10 L 15 10 M 15 10 L 10 5 M 15 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 화살표 패스 데이터 속성 - ArrowPathDataProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowPathDataProperty = DependencyProperty.Register ( "ArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15") ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 채우기 - BackgroundEllipseFill /// <summary> /// 배경 원 채우기 /// </summary> public Brush BackgroundEllipseFill { get => (Brush)GetValue(BackgroundEllipseFillProperty); set => SetValue(BackgroundEllipseFillProperty, value); } #endregion #region 배경 원 스트로크 두께 - BackgroundEllipseStrokeThickness /// <summary> /// 배경 원 스트로크 두께 /// </summary> public Thickness BackgroundEllipseStrokeThickness { get => (Thickness)GetValue(BackgroundEllipseStrokeThicknessProperty); set => SetValue(BackgroundEllipseStrokeThicknessProperty, value); } #endregion #region 배경 원 스트로크 - BackgroundEllipseStroke /// <summary> /// 배경 원 스트로크 /// </summary> public Brush BackgroundEllipseStroke { get => (Brush)GetValue(BackgroundEllipseStrokeProperty); set => SetValue(BackgroundEllipseStrokeProperty, value); } #endregion #region 화살표 크기 - ArrowSize /// <summary> /// 화살표 크기 /// </summary> public double ArrowSize { get => (double)GetValue(ArrowSizeProperty); set => SetValue(ArrowSizeProperty, value); } #endregion #region 화살표 방향 - ArrowDirection /// <summary> /// 화살표 방향 /// </summary> public ArrowDirection ArrowDirection { get => (ArrowDirection)GetValue(ArrowDirectionProperty); set => SetValue(ArrowDirectionProperty, value); } #endregion #region 화살표 스트로크 두께 - ArrowStrokeThickness /// <summary> /// 화살표 스트로크 두께 /// </summary> public Thickness ArrowStrokeThickness { get => (Thickness)GetValue(ArrowStrokeThicknessProperty); set => SetValue(ArrowStrokeThicknessProperty, value); } #endregion #region 화살표 스트로크 - ArrowStroke /// <summary> /// 화살표 스트로크 /// </summary> public Brush ArrowStroke { get => (Brush)GetValue(ArrowStrokeProperty); set => SetValue(ArrowStrokeProperty, value); } #endregion #region 왼쪽 화살표 패스 데이터 - LeftArrowPathData /// <summary> /// 왼쪽 화살표 패스 데이터 /// </summary> public string LeftArrowPathData { get => (string)GetValue(LeftArrowPathDataProperty); set => SetValue(LeftArrowPathDataProperty, value); } #endregion #region 오른쪽 화살표 패스 데이터 - RightArrowPathData /// <summary> /// 오른쪽 화살표 패스 데이터 /// </summary> public string RightArrowPathData { get => (string)GetValue(RightArrowPathDataProperty); set => SetValue(RightArrowPathDataProperty, value); } #endregion #region 화살표 패스 데이터 - ArrowPathData /// <summary> /// 화살표 패스 데이터 /// </summary> public string ArrowPathData { get => (string)GetValue(ArrowPathDataProperty); private set => SetValue(ArrowPathDataProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ArrowButton() /// <summary> /// 생성자 /// </summary> static ArrowButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ArrowButton), new FrameworkPropertyMetadata(typeof(ArrowButton))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 방향 속성 변경시 콜백 처리하기 - DirectionPropertyChangedCallback(d, e) /// <summary> /// 방향 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void DirectionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion #region 화살표 패스 데이터 속성 변경시 콜백 처리하기 - ArrowPathDataPropertyChangedCallback(d, e) /// <summary> /// 화살표 패스 데이터 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ArrowPathDataPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region 화살표 패스 데이터 업데이트하기 - UpdateArrowPathData() /// <summary> /// 화살표 패스 데이터 업데이트하기 /// </summary> private void UpdateArrowPathData() { ArrowPathData = ArrowDirection == ArrowDirection.Left ? LeftArrowPathData : RightArrowPathData; } #endregion } |
▶ ArrowDirection.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
namespace TestProject; /// <summary> /// 화살표 방향 /// </summary> public enum ArrowDirection { Left, Right } |
▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ArrowButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ArrowButton}"> <Grid Name="grid"> <Ellipse Name="backgroundEllipse" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStroke}" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseFill}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ArrowSize}" Height="{TemplateBinding ArrowSize}" Margin="{TemplateBinding Padding}"> <Canvas Width="20" Height="20"> <Path Name="arrowPath" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStroke}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Data="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowPathData}" /> </Canvas> </Viewbox> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#e0e0e0" /> <Setter TargetName="arrowPath" Property="Stroke" Value="Black" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#bdbdbd" /> <Setter TargetName="grid" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="1" Y="1" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Width" Value="32" /> <Setter Property="Height" Value="32" /> <Setter Property="ArrowSize" Value="20" /> </Style> <Style TargetType="{x:Type local:RoundImage}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:RoundImage}"> <Border Name="PART_RootBorder" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}"> <ContentPresenter /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="{x:Type local:ImageCarousel}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ImageCarousel}"> <Border CornerRadius="10" Background="{TemplateBinding Background}"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="10" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="5" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="5" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <local:ArrowButton x:Name="PART_PreviousArrowButton" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" Width="32" Height="32" BackgroundEllipseStrokeThickness="1" BackgroundEllipseStroke="LightGray" ArrowDirection="Left" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="Black" LeftArrowPathData="M 7 10 L 12 5 M 7 10 L 12 15" RightArrowPathData="M 13 10 L 8 5 M 13 10 L 8 15"> <local:ArrowButton.BackgroundEllipseFill> <SolidColorBrush> <SolidColorBrush.Color> <Color A="127" R="255" G="255" B="255" /> </SolidColorBrush.Color> </SolidColorBrush> </local:ArrowButton.BackgroundEllipseFill> </local:ArrowButton> <local:RoundImage x:Name="PART_RoundImage" Grid.Row="0" Grid.Column="2" Margin="0 0 0 15"> </local:RoundImage> <Border Grid.Row="0" Grid.RowSpan="2" Grid.Column="2" Margin="10" VerticalAlignment="Bottom" CornerRadius="10" BorderThickness="1" BorderBrush="DarkGray" Background="#e0ffffff" Padding="10"> <TextBlock Name="PART_DescriptionTextBlock" HorizontalAlignment="Center" Foreground="Black" TextWrapping="Wrap" /> </Border> <local:ArrowButton x:Name="PART_NextArrowButton" Grid.Row="0" Grid.RowSpan="2" Grid.Column="4" VerticalAlignment="Center" HorizontalAlignment="Right" Width="32" Height="32" BackgroundEllipseStrokeThickness="1" BackgroundEllipseStroke="LightGray" ArrowDirection="Right" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="Black" LeftArrowPathData="M 7 10 L 12 5 M 7 10 L 12 15" RightArrowPathData="M 13 10 L 8 5 M 13 10 L 8 15"> <local:ArrowButton.BackgroundEllipseFill> <SolidColorBrush> <SolidColorBrush.Color> <Color A="192" R="255" G="255" B="255" /> </SolidColorBrush.Color> </SolidColorBrush> </local:ArrowButton.BackgroundEllipseFill> </local:ArrowButton> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ ImageCarousel.cs
■ Control 클래스를 사용해 라운드 이미지 컨트롤을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:RoundImage}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:RoundImage}"> <Border Name="PART_RootBorder" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}"> <ContentPresenter /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ RoundImage.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 라운드 이미지 /// </summary> public class RoundImage : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 속성 - CornerRadiusProperty /// <summary> /// 코너 반경 속성 /// </summary> public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register ( "CornerRadius", typeof(CornerRadius), typeof(RoundImage), new PropertyMetadata(new CornerRadius(10)) ); #endregion #region 스트레치 속성 - StretchProperty /// <summary> /// 스트레치 속성 /// </summary> public static readonly DependencyProperty StretchProperty = DependencyProperty.Register ( "Stretch", typeof(Stretch), typeof(RoundImage), new PropertyMetadata(Stretch.UniformToFill, StretchPropertyChangedCallback) ); #endregion #region 이미지 소스 속성 - ImageSourceProperty /// <summary> /// 이미지 소스 속성 /// </summary> public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register ( "ImageSource", typeof(ImageSource), typeof(RoundImage), new PropertyMetadata(null, ImageSourcePropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 루트 테두리 /// </summary> private Border rootBorder = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 - CornerRadius /// <summary> /// 코너 반경 /// </summary> public CornerRadius CornerRadius { get => (CornerRadius)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } #endregion #region 스트레치 - Stretch /// <summary> /// 스트레치 /// </summary> public Stretch Stretch { get => (Stretch)GetValue(StretchProperty); set => SetValue(StretchProperty, value); } #endregion #region 이미지 소스 - ImageSource /// <summary> /// 이미지 소스 /// </summary> public ImageSource ImageSource { get => (ImageSource)GetValue(ImageSourceProperty); set => SetValue(ImageSourceProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - RoundImage() /// <summary> /// 생성자 /// </summary> static RoundImage() { DefaultStyleKeyProperty.OverrideMetadata(typeof(RoundImage), new FrameworkPropertyMetadata(typeof(RoundImage))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - RoundImage() /// <summary> /// 생성자 /// </summary> public RoundImage() { Loaded += Control_Loaded; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static #region 스트레치 속성 변경시 콜백 처리하기 - StretchPropertyChangedCallback(d, e) /// <summary> /// 스트레치 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void StretchPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is RoundImage roundImage) { roundImage.UpdateBackground(); } } #endregion #region 이미지 소스 속성 변경시 콜백 처리하기 - ImageSourcePropertyChangedCallback(d, e) /// <summary> /// 이미지 소스 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ImageSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is RoundImage roundImage) { roundImage.UpdateBackground(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public ////////////////////////////////////////////////////////////////////// Function #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.rootBorder = GetTemplateChild("PART_RootBorder") as Border; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 컨트롤 로드시 처리하기 - Control_Loaded(sender, e) /// <summary> /// 컨트롤 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Control_Loaded(object sender, RoutedEventArgs e) { UpdateBackground(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 배경 업데이트하기 - UpdateBackground() /// <summary> /// 배경 업데이트하기 /// </summary> private void UpdateBackground() { if(this.rootBorder == null) { return; } if(ImageSource != null) { this.rootBorder.Background = new ImageBrush { ImageSource = this.ImageSource, Stretch = this.Stretch }; } else { this.rootBorder.Background = null; } } #endregion } |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="CONTROL/ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <local:RoundImage x:Name="roundImage1" BorderThickness="3" BorderBrush="DarkGray" Width="300" Height="200" CornerRadius="20" ImageSource="IMAGE/image1.jpg"> </local:RoundImage> <local:RoundImage x:Name="roundImage2" Margin="0 10 0 0" BorderThickness="3" BorderBrush="DarkGray" Width="300" Height="200" CornerRadius="20"> </local:RoundImage> </StackPanel> </Window> |
■ Button 클래스를 사용해 화살표 원 버튼을 만드는 방법을 보여준다. ▶ ArrowButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 화살표 버튼 /// </summary> public class ArrowButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 스트로크 두께 속성 - BackgroundEllipseStrokeThicknessProperty /// <summary> /// 배경 원 두께 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeThicknessProperty = DependencyProperty.Register ( "BackgroundEllipseStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(0)) ); #endregion #region 배경 원 스트로크 속성 - BackgroundEllipseStrokeProperty /// <summary> /// 배경 원 패스 데이터 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeProperty = DependencyProperty.Register ( "BackgroundEllipseStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 배경 원 채우기 속성 - BackgroundEllipseFillProperty /// <summary> /// 배경 원 채우기 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseFillProperty = DependencyProperty.Register ( "BackgroundEllipseFill", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 화살표 크기 속성 - ArrowSizeProperty /// <summary> /// 화살표 크기 속성 /// </summary> public static readonly DependencyProperty ArrowSizeProperty = DependencyProperty.Register ( "ArrowSize", typeof(double), typeof(ArrowButton), new PropertyMetadata(20.0) ); #endregion #region 화살표 방향 속성 - ArrowDirectionProperty /// <summary> /// 화살표 방향 속성 /// </summary> public static readonly DependencyProperty ArrowDirectionProperty = DependencyProperty.Register ( "ArrowDirection", typeof(ArrowDirection), typeof(ArrowButton), new PropertyMetadata(ArrowDirection.Left, DirectionPropertyChangedCallback) ); #endregion #region 화살표 스트로크 두께 속성 - ArrowStrokeThicknessProperty /// <summary> /// 화살표 두께 /// </summary> public static readonly DependencyProperty ArrowStrokeThicknessProperty = DependencyProperty.Register ( "ArrowStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(1)) ); #endregion #region 화살표 스트로크 속성 - ArrowStrokeProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowStrokeProperty = DependencyProperty.Register ( "ArrowStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Black) ); #endregion #region 왼쪽 화살표 패스 데이터 속성 - LeftArrowPathDataProperty /// <summary> /// 왼쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty LeftArrowPathDataProperty = DependencyProperty.Register ( "LeftArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 오른쪽 화살표 패스 데이터 속성 - RightArrowPathDataProperty /// <summary> /// 오른쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty RightArrowPathDataProperty = DependencyProperty.Register ( "RightArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 5 10 L 15 10 M 15 10 L 10 5 M 15 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 화살표 패스 데이터 속성 - ArrowPathDataProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowPathDataProperty = DependencyProperty.Register ( "ArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15") ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 채우기 - BackgroundEllipseFill /// <summary> /// 배경 원 채우기 /// </summary> public Brush BackgroundEllipseFill { get => (Brush)GetValue(BackgroundEllipseFillProperty); set => SetValue(BackgroundEllipseFillProperty, value); } #endregion #region 배경 원 스트로크 두께 - BackgroundEllipseStrokeThickness /// <summary> /// 배경 원 스트로크 두께 /// </summary> public Thickness BackgroundEllipseStrokeThickness { get => (Thickness)GetValue(BackgroundEllipseStrokeThicknessProperty); set => SetValue(BackgroundEllipseStrokeThicknessProperty, value); } #endregion #region 배경 원 스트로크 - BackgroundEllipseStroke /// <summary> /// 배경 원 스트로크 /// </summary> public Brush BackgroundEllipseStroke { get => (Brush)GetValue(BackgroundEllipseStrokeProperty); set => SetValue(BackgroundEllipseStrokeProperty, value); } #endregion #region 화살표 크기 - ArrowSize /// <summary> /// 화살표 크기 /// </summary> public double ArrowSize { get => (double)GetValue(ArrowSizeProperty); set => SetValue(ArrowSizeProperty, value); } #endregion #region 화살표 방향 - ArrowDirection /// <summary> /// 화살표 방향 /// </summary> public ArrowDirection ArrowDirection { get => (ArrowDirection)GetValue(ArrowDirectionProperty); set => SetValue(ArrowDirectionProperty, value); } #endregion #region 화살표 스트로크 두께 - ArrowStrokeThickness /// <summary> /// 화살표 스트로크 두께 /// </summary> public Thickness ArrowStrokeThickness { get => (Thickness)GetValue(ArrowStrokeThicknessProperty); set => SetValue(ArrowStrokeThicknessProperty, value); } #endregion #region 화살표 스트로크 - ArrowStroke /// <summary> /// 화살표 스트로크 /// </summary> public Brush ArrowStroke { get => (Brush)GetValue(ArrowStrokeProperty); set => SetValue(ArrowStrokeProperty, value); } #endregion #region 왼쪽 화살표 패스 데이터 - LeftArrowPathData /// <summary> /// 왼쪽 화살표 패스 데이터 /// </summary> public string LeftArrowPathData { get => (string)GetValue(LeftArrowPathDataProperty); set => SetValue(LeftArrowPathDataProperty, value); } #endregion #region 오른쪽 화살표 패스 데이터 - RightArrowPathData /// <summary> /// 오른쪽 화살표 패스 데이터 /// </summary> public string RightArrowPathData { get => (string)GetValue(RightArrowPathDataProperty); set => SetValue(RightArrowPathDataProperty, value); } #endregion #region 화살표 패스 데이터 - ArrowPathData /// <summary> /// 화살표 패스 데이터 /// </summary> public string ArrowPathData { get => (string)GetValue(ArrowPathDataProperty); private set => SetValue(ArrowPathDataProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ArrowButton() /// <summary> /// 생성자 /// </summary> static ArrowButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ArrowButton), new FrameworkPropertyMetadata(typeof(ArrowButton))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 방향 속성 변경시 콜백 처리하기 - DirectionPropertyChangedCallback(d, e) /// <summary> /// 방향 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void DirectionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion #region 화살표 패스 데이터 속성 변경시 콜백 처리하기 - ArrowPathDataPropertyChangedCallback(d, e) /// <summary> /// 화살표 패스 데이터 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ArrowPathDataPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region 화살표 패스 데이터 업데이트하기 - UpdateArrowPathData() /// <summary> /// 화살표 패스 데이터 업데이트하기 /// </summary> private void UpdateArrowPathData() { ArrowPathData = ArrowDirection == ArrowDirection.Left ? LeftArrowPathData : RightArrowPathData; } #endregion } |
▶ ArrowDirection.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
namespace TestProject; /// <summary> /// 화살표 방향 /// </summary> public enum ArrowDirection { Left, Right } |
▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ArrowButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ArrowButton}"> <Grid Name="grid"> <Ellipse Name="backgroundEllipse" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStroke}" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseFill}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ArrowSize}" Height="{TemplateBinding ArrowSize}" Margin="{TemplateBinding Padding}"> <Canvas Width="20" Height="20"> <Path Name="arrowPath" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStroke}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Data="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowPathData}" /> </Canvas> </Viewbox> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#e0e0e0" /> <Setter TargetName="arrowPath" Property="Stroke" Value="Black" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#bdbdbd" /> <Setter TargetName="grid" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="1" Y="1" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Width" Value="32" /> <Setter Property="Height" Value="32" /> <Setter Property="ArrowSize" Value="20" /> </Style> </ResourceDictionary> |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
■ Button 엘리먼트를 사용해 새 채팅 아이콘 버튼을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:NewChatButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:NewChatButton}"> <Grid> <Viewbox Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"> <Canvas Width="40" Height="40"> <Ellipse Name="PART_BackgroundEllipse" Canvas.Left="1" Canvas.Top="1" Width="40" Height="40" Fill="{TemplateBinding Foreground}" /> <Path Name="PART_ChatBubblePath" StrokeThickness="3" Stroke="White" Fill="Transparent"> <Path.Data> <GeometryGroup> <EllipseGeometry Center="20 20" RadiusX="12" RadiusY="12" /> <PathGeometry Figures="M 20 32 L 16 36 L 16 32 Z" /> </GeometryGroup> </Path.Data> </Path> <Ellipse Name="PART_PlusSignEllipse" Canvas.Left="22" Canvas.Top="22" Width="14" Height="14" Fill="White" /> <Path Name="PART_PlusSignPath" Canvas.Left="-1" Canvas.Top="-1" StrokeThickness="2" Stroke="{TemplateBinding Foreground}" Data="M 30 26 V 34 M 26 30 H 34" /> </Canvas> </Viewbox> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="PART_BackgroundEllipse" Property="Fill" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MouseOverBrush}" /> <Setter TargetName="PART_PlusSignPath" Property="Stroke" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MouseOverBrush}" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="PART_BackgroundEllipse" Property="Fill" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=PressedBrush}" /> <Setter TargetName="PART_PlusSignPath" Property="Stroke" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=PressedBrush}" /> <Setter Property="RenderTransform"> <Setter.Value> <ScaleTransform CenterX="20" CenterY="20" ScaleX="0.95" ScaleY="0.95" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Width" Value="40" /> <Setter Property="Height" Value="40" /> <Setter Property="BorderThickness" Value="0" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="Foreground" Value="#0762c1" /> <Setter Property="MouseOverBrush" Value="#1976d2" /> <Setter Property="PressedBrush" Value="#0d47a1" /> </Style> </ResourceDictionary> |
▶ NewChatButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 새 채팅 버튼 /// </summary> public class NewChatButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// DependencyProperty ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 마우스 오버 브러시 속성 - MouseOverBrushProperty /// <summary> /// 마우스 오버 브러시 속성 /// </summary> public static readonly DependencyProperty MouseOverBrushProperty = DependencyProperty.Register ( nameof(MouseOverBrush), typeof(Brush), typeof(NewChatButton), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(0x19, 0x76, 0xd2))) ); #endregion #region PRESS 브러시 속성 - PressedBrushProperty /// <summary> /// PRESS 브러시 속성 /// </summary> public static readonly DependencyProperty PressedBrushProperty = DependencyProperty.Register ( nameof(PressedBrush), typeof(Brush), typeof(NewChatButton), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(0x0d, 0x47, 0xa1))) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 마우스 오버 브러시 - MouseOverBrush /// <summary> /// 마우스 오버 브러시 /// </summary> public Brush MouseOverBrush { get => (Brush)GetValue(MouseOverBrushProperty); set => SetValue(MouseOverBrushProperty, value); } #endregion #region PRESS 브러시 - PressedBrush /// <summary> /// PRESS 브러시 /// </summary> public Brush PressedBrush { get => (Brush)GetValue(PressedBrushProperty); set => SetValue(PressedBrushProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - NewChatButton() /// <summary> /// 생성자 /// </summary> static NewChatButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(NewChatButton), new FrameworkPropertyMetadata(typeof(NewChatButton))); } #endregion } |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="CONTROL/ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
■ ListBox 엘리먼트의 Style 속성을 사용해의 리스트 박스에 글래스 효과를 설정하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" Background="#2d2d2d" FontFamily="나눔고딕코딩" FontSize="16"> <Window.Resources> <Style x:Key="GlassListBoxItemStyleKey" TargetType="ListBoxItem"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="Transparent" /> <Setter Property="Padding" Value="4 1" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="SnapsToDevicePixels" Value="True" /> <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/> <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment , RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Border Name="border" Margin="2" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true"> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="border" Property="Background" > <Setter.Value> <LinearGradientBrush StartPoint="0 0" EndPoint="0 1"> <GradientStop Offset="0" Color="#20ffffff" /> <GradientStop Offset="1" Color="#10ffffff" /> </LinearGradientBrush> </Setter.Value> </Setter> <Setter TargetName="border" Property="BorderBrush" Value="#50ffffff" /> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter TargetName="border" Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0 0" EndPoint="0 1"> <GradientStop Offset="0" Color="#40ffffff" /> <GradientStop Offset="1" Color="#20ffffff" /> </LinearGradientBrush> </Setter.Value> </Setter> <Setter TargetName="border" Property="BorderBrush" Value="#80ffffff" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="GlassListBoxStyleKey" TargetType="ListBox"> <Setter Property="ItemContainerStyle" Value="{StaticResource GlassListBoxItemStyleKey}"/> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="#20ffffff" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" /> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" /> </Style> </Window.Resources> <ListBox Style="{StaticResource GlassListBoxStyleKey}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="300" Height="300" Foreground="White"> <ListBoxItem>항목 01</ListBoxItem> <ListBoxItem>항목 02</ListBoxItem> <ListBoxItem>항목 03</ListBoxItem> <ListBoxItem>항목 04</ListBoxItem> <ListBoxItem>항목 05</ListBoxItem> <ListBoxItem>항목 06</ListBoxItem> <ListBoxItem>항목 07</ListBoxItem> <ListBoxItem>항목 08</ListBoxItem> <ListBoxItem>항목 09</ListBoxItem> <ListBoxItem>항목 10</ListBoxItem> </ListBox> </Window> |
TestProject.zip
■ ControlTemplate 엘리먼트를 사용해 Button 엘리먼트를 정의하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <Window.Resources> <SolidColorBrush x:Key="BackgroundBorderDisabledBackgroundBrushKey" Color="#fff4f4f4" /> <SolidColorBrush x:Key="HoverBorderBackgroundBrushKey" Color="#ff939393" /> <SolidColorBrush x:Key="hoverShineBorderBackgroundBrushKey" Color="#ffaaaaaa" /> <LinearGradientBrush x:Key="PressedBorderBackgroundBrushKey" StartPoint="0.5 0.042" EndPoint="0.5 0.971"> <GradientStop Offset="0" Color="#4c000000" /> <GradientStop Offset="1" Color="#26ffffff" /> <GradientStop Offset="0.467" Color="#4c000000" /> <GradientStop Offset="0.479" Color="#26ffffff" /> </LinearGradientBrush> <LinearGradientBrush x:Key="ShineBorderBackgroundBrushKey" StartPoint="0.5 0.042" EndPoint="0.5 0.971"> <GradientStop Offset="0" Color="#26ffffff" /> <GradientStop Offset="1" Color="#00ffffff" /> <GradientStop Offset="0.467" Color="#26ffffff" /> <GradientStop Offset="0.475" Color="#00ffffff" /> </LinearGradientBrush> <SolidColorBrush x:Key="ShineBorderDisabledBorderBrushKey" Color="#ffadb2b5" /> <ControlTemplate x:Key="ButtonTemplateKey" TargetType="{x:Type Button}"> <ControlTemplate.Resources> <Storyboard x:Key="HoverOnStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hoverShineBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hoverBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="HoverOffStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hoverShineBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hoverBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="PressedOnStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="pressedBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="PressedOffStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="pressedBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="FocusedOnStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="focusBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="FocussedOffStorybardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="focusBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> </ControlTemplate.Resources> <Grid Name="grid"> <Border Name="backgroundBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" /> <Border Name="hoverBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{StaticResource HoverBorderBackgroundBrushKey}" Opacity="0" /> <Border Name="hoverShineBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{StaticResource hoverShineBorderBackgroundBrushKey}" Opacity="0" /> <Border Name="pressedBorder" CornerRadius="3" Background="{StaticResource PressedBorderBackgroundBrushKey}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Opacity="0" /> <Border Name="shineBorder" CornerRadius="3" Background="{StaticResource ShineBorderBackgroundBrushKey}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Opacity="1" /> <ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True" /> <Border Name="focusBorder" Margin="1 1 1 1" CornerRadius="3 3 3 3" BorderThickness="1" BorderBrush="{StaticResource hoverShineBorderBackgroundBrushKey}" IsHitTestVisible="false" Opacity="0" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsKeyboardFocused" Value="true"> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource FocussedOffStorybardKey}" /> </Trigger.ExitActions> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource FocusedOnStoryboardKey}" /> </Trigger.EnterActions> </Trigger> <Trigger Property="IsMouseOver" Value="true"> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource HoverOffStoryboardKey}" /> </Trigger.ExitActions> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource HoverOnStoryboardKey}" /> </Trigger.EnterActions> </Trigger> <Trigger Property="IsPressed" Value="true"> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource PressedOffStoryboardKey}" /> </Trigger.ExitActions> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource PressedOnStoryboardKey}" /> </Trigger.EnterActions> </Trigger> <Trigger Property="IsEnabled" Value="true" /> <Trigger Property="IsEnabled" Value="false"> <Setter TargetName="backgroundBorder" Property="Background" Value="{DynamicResource BackgroundBorderDisabledBackgroundBrushKey}" /> <Setter TargetName="shineBorder" Property="BorderBrush" Value="{DynamicResource ShineBorderDisabledBorderBrushKey}" /> <Setter TargetName="grid" Property="Opacity" Value="0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> <Style x:Key="ButtonFocusVisualStyleKey"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate> <Border> <Rectangle Margin="2" StrokeThickness="1" StrokeDashArray="1 2" Stroke="#60000000" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <SolidColorBrush x:Key="ButtonBorderBrushKey" Color="#ff707070" /> <SolidColorBrush x:Key="ButtonBackgroundBrushKey" Color="#ff818181" /> <SolidColorBrush x:Key="ButtonForegroundBrushKey" Color="#ff000000" /> <Style TargetType="{x:Type Button}" BasedOn="{x:Null}"> <Setter Property="Template" Value="{DynamicResource ButtonTemplateKey}" /> <Setter Property="FocusVisualStyle" Value="{DynamicResource ButtonFocusVisualStyleKey}" /> <Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushKey}" /> <Setter Property="Background" Value="{DynamicResource ButtonBackgroundBrushKey}" /> <Setter Property="Foreground" Value="{DynamicResource ButtonForegroundBrushKey}" /> </Style> </Window.Resources> <Button HorizontalAlignment="Center" VerticalAlignment="Center" Padding="10" Foreground="White" Content="선택" /> </Window> |
TestProject.zip
■ ControlTemplate 엘리먼트를 사용해 Button 엘리먼트를 정의하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <Window.Resources> <SolidColorBrush x:Key="BackgroundBorderDisabledBackgroundBrushKey" Color="#ff787878" /> <SolidColorBrush x:Key="BackgroundBorderDisabledBorderBrushKey" Color="#aaa" /> <SolidColorBrush x:Key="HoverBorderBackgroundBrushKey" Color="#ff393939" /> <LinearGradientBrush x:Key="HoverShineBorderBackgroundBrushKey" StartPoint="0.5 0.042" EndPoint="0.5 0.971"> <GradientStop Offset="0" Color="#4cffffff" /> <GradientStop Offset="1" Color="#26ffffff" /> <GradientStop Offset="0.467" Color="#26ffffff" /> <GradientStop Offset="0.475" Color="#00ffffff" /> <GradientStop Offset="0.856" Color="#00ffffff" /> </LinearGradientBrush> <LinearGradientBrush x:Key="PressedBorderBackgroundBrushKey" StartPoint="0.5 0.042" EndPoint="0.5 0.971"> <GradientStop Offset="0" Color="#4c000000" /> <GradientStop Offset="1" Color="#26ffffff" /> <GradientStop Offset="0.467" Color="#4c000000" /> <GradientStop Offset="0.479" Color="#26ffffff" /> </LinearGradientBrush> <SolidColorBrush x:Key="ShineBorderDefaultBorderBrushKey" Color="#ff9bb1c5" /> <LinearGradientBrush x:Key="ShineBoderBackgroundBrushKey" StartPoint="0.5 0.042" EndPoint="0.5 0.971"> <GradientStop Offset="0" Color="#59ffffff" /> <GradientStop Offset="1" Color="#00ffffff" /> <GradientStop Offset="0.467" Color="#26ffffff" /> <GradientStop Offset="0.475" Color="#00ffffff" /> </LinearGradientBrush> <ControlTemplate x:Key="ButtonTemplateKey" TargetType="{x:Type Button}"> <ControlTemplate.Resources> <Storyboard x:Key="HoverOnStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hovershineBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hoverBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="hoverOffStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hovershineBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="hoverBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="pressedOnStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="pressedBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="pressedOffStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="pressedBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="focusedOnStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="focusBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="focussedOffStoryboardKey"> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="focusBorder" Storyboard.TargetProperty="(UIElement.Opacity)" BeginTime="00:00:00"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> </ControlTemplate.Resources> <Grid Name="grid"> <Border Name="backgroundBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" /> <Border Name="hoverBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{StaticResource HoverBorderBackgroundBrushKey}" Opacity="0" /> <Border Name="hovershineBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{StaticResource HoverShineBorderBackgroundBrushKey}" Opacity="0" /> <Border Name="pressedBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{StaticResource PressedBorderBackgroundBrushKey}" Opacity="0" /> <Border Name="shineBorder" CornerRadius="3" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{StaticResource ShineBoderBackgroundBrushKey}" Opacity="1" /> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" /> <Border Name="focusBorder" Margin="1 1 1 1" CornerRadius="3 3 3 3" BorderThickness="1" BorderBrush="{StaticResource HoverShineBorderBackgroundBrushKey}" IsHitTestVisible="false" Opacity="0" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsDefault" Value="True"> <Setter TargetName="shineBorder" Property="BorderBrush" Value="{DynamicResource ShineBorderDefaultBorderBrushKey}" /> </Trigger> <Trigger Property="IsKeyboardFocused" Value="true"> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource focussedOffStoryboardKey}" /> </Trigger.ExitActions> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource focusedOnStoryboardKey}" /> </Trigger.EnterActions> </Trigger> <Trigger Property="IsMouseOver" Value="true"> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource hoverOffStoryboardKey}" /> </Trigger.ExitActions> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource HoverOnStoryboardKey}" /> </Trigger.EnterActions> </Trigger> <Trigger Property="IsPressed" Value="true"> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource pressedOffStoryboardKey}" /> </Trigger.ExitActions> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource pressedOnStoryboardKey}" /> </Trigger.EnterActions> </Trigger> <Trigger Property="IsEnabled" Value="true" /> <Trigger Property="IsEnabled" Value="false"> <Setter TargetName="backgroundBorder" Property="Background" Value="{DynamicResource BackgroundBorderDisabledBackgroundBrushKey}" /> <Setter TargetName="shineBorder" Property="BorderBrush" Value="{DynamicResource BackgroundBorderDisabledBorderBrushKey}" /> <Setter TargetName="grid" Property="Opacity" Value="0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> <Style x:Key="FocusVisualStyleKey"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate> <Border> <Rectangle Margin="2" StrokeThickness="1" StrokeDashArray="1 2" Stroke="#60000000" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <SolidColorBrush x:Key="ButtonBorderBrushKey" Color="#ff333333" /> <SolidColorBrush x:Key="ButtonBackgroundBrushKey" Color="#ff595959" /> <SolidColorBrush x:Key="ButtonForegroundBrushKey" Color="#ffffffff" /> <Style TargetType="{x:Type Button}" BasedOn="{x:Null}"> <Setter Property="Template" Value="{DynamicResource ButtonTemplateKey}" /> <Setter Property="FocusVisualStyle" Value="{DynamicResource FocusVisualStyleKey}" /> <Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushKey}" /> <Setter Property="Background" Value="{DynamicResource ButtonBackgroundBrushKey}" /> <Setter Property="Foreground" Value="{DynamicResource ButtonForegroundBrushKey}" /> </Style> </Window.Resources> <Button HorizontalAlignment="Center" VerticalAlignment="Center" Padding="10" Foreground="White" Content="선택" /> </Window> |
TestProject.zip
■ Button 엘리먼트를 사용해 PATH 아이콘과 텍스트를 표시하는 버튼을 만드는 방법을 보여준다. ▶ PathIconButton.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<Button x:Class="TestProject.PathIconButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Button.Template> <ControlTemplate TargetType="Button"> <Border Name="border" CornerRadius="10" Padding="5" Background="{TemplateBinding Background}"> <StackPanel Margin="{TemplateBinding Padding}" Orientation="Horizontal"> <Path Name="path" VerticalAlignment="Center" Margin="0 0 0 0" Width="{Binding PathWidth, RelativeSource={RelativeSource TemplatedParent}}" Height="{Binding PathHeight, RelativeSource={RelativeSource TemplatedParent}}" Stretch="Uniform" Fill="{TemplateBinding Foreground}" Data="{Binding PathData, RelativeSource={RelativeSource TemplatedParent}}" /> <ContentPresenter Name="contentPresenter" VerticalAlignment="Center" Content="{TemplateBinding Content}"> <ContentPresenter.Style> <Style TargetType="ContentPresenter"> <Setter Property="Margin" Value="10 0 0 0" /> <Setter Property="Visibility" Value="Visible" /> <Style.Triggers> <DataTrigger Binding="{Binding Content, RelativeSource={RelativeSource Self}}" Value="{x:Null}"> <Setter Property="Margin" Value="0" /> <Setter Property="Visibility" Value="Collapsed" /> </DataTrigger> </Style.Triggers> </Style> </ContentPresenter.Style> </ContentPresenter> </StackPanel> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="border" Property="Background" Value="{Binding MouseOverBrush, RelativeSource={RelativeSource TemplatedParent}}" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="border" Property="Background" Value="{Binding PressedBrush, RelativeSource={RelativeSource TemplatedParent}}" /> <Setter TargetName="border" Property="RenderTransform"> <Setter.Value> <TranslateTransform Y="2" /> </Setter.Value> </Setter> <Setter TargetName="path" Property="RenderTransform"> <Setter.Value> <TranslateTransform Y="1" /> </Setter.Value> </Setter> <Setter TargetName="contentPresenter" Property="RenderTransform"> <Setter.Value> <TranslateTransform Y="1" /> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="border" Property="Background" Value="DarkGray" /> <Setter TargetName="path" Property="Fill" Value="LightGray" /> <Setter TargetName="contentPresenter" Property="IsEnabled" Value="False" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Button.Template> </Button> |
▶ PathIconButton.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 패스 아이콘 버튼 /// </summary> public partial class PathIconButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 마우스 오버 브러시 속성 - MouseOverBrushProperty /// <summary> /// 마우스 오버 브러시 속성 /// </summary> public static readonly DependencyProperty MouseOverBrushProperty = DependencyProperty.Register ( nameof(MouseOverBrush), typeof(Brush), typeof(PathIconButton), new PropertyMetadata(null) ); #endregion #region 프레스 브러시 속성 - PressedBrushProperty /// <summary> /// 프레스 브러시 속성 /// </summary> public static readonly DependencyProperty PressedBrushProperty = DependencyProperty.Register ( nameof(PressedBrush), typeof(Brush), typeof(PathIconButton), new PropertyMetadata(null) ); #endregion #region 패스 너비 속성 - PathWidthProperty /// <summary> /// 패스 너비 속성 /// </summary> public static readonly DependencyProperty PathWidthProperty = DependencyProperty.Register ( nameof(PathWidth), typeof(double), typeof(PathIconButton), new PropertyMetadata(16d) ); #endregion #region 패스 높이 속성 - PathHeightProperty /// <summary> /// 패스 높이 속성 /// </summary> public static readonly DependencyProperty PathHeightProperty = DependencyProperty.Register ( nameof(PathHeight), typeof(double), typeof(PathIconButton), new PropertyMetadata(16d) ); #endregion #region 패스 데이터 속성 - PathDataProperty /// <summary> /// 패스 데이터 속성 /// </summary> public static readonly DependencyProperty PathDataProperty = DependencyProperty.Register ( nameof(PathData), typeof(Geometry), typeof(PathIconButton), new PropertyMetadata(null) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 마우스 오버 브러시 - MouseOverBrush /// <summary> /// 마우스 오버 브러시 /// </summary> public Brush MouseOverBrush { get { return (Brush)GetValue(MouseOverBrushProperty); } set { SetValue(MouseOverBrushProperty, value); } } #endregion #region 프레스 브러시 - PressedBrush /// <summary> /// 프레스 브러시 /// </summary> public Brush PressedBrush { get { return (Brush)GetValue(PressedBrushProperty); } set { SetValue(PressedBrushProperty, value); } } #endregion #region 패스 너비 - PathWidth /// <summary> /// 패스 너비 /// </summary> public double PathWidth { get { return (double)GetValue(PathWidthProperty); } set { SetValue(PathWidthProperty, value); } } #endregion #region 패스 높이 - PathHeight /// <summary> /// 패스 높이 /// </summary> public double PathHeight { get { return (double)GetValue(PathHeightProperty); } set { SetValue(PathHeightProperty, value); } } #endregion #region 패스 데이터 - PathData /// <summary> /// 패스 데이터 /// </summary> public Geometry PathData { get { return (Geometry)GetValue(PathDataProperty); } set { SetValue(PathDataProperty, value); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - PathIconButton() /// <summary> /// 생성자 /// </summary> public PathIconButton() { InitializeComponent(); } #endregion } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="맑은고딕" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <local:PathIconButton HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Padding="10" Background="#007bff" Foreground="White" MouseOverBrush="#0056b3" PressedBrush="#004085" PathWidth="20" PathHeight="20"> <local:PathIconButton.PathData> <Geometry>M 2.01 21 L 23 12 2.01 3 2 10 l 15 2 -15 2 z</Geometry> </local:PathIconButton.PathData> <TextBlock VerticalAlignment="Center" Text="작업 전송" /> </local:PathIconButton> <local:PathIconButton HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Padding="10" Background="#007bff" Foreground="White" MouseOverBrush="#0056b3" PressedBrush="#004085" PathWidth="20" PathHeight="20" IsEnabled="False"> <local:PathIconButton.PathData> <Geometry>M 2.01 21 L 23 12 2.01 3 2 10 l 15 2 -15 2 z</Geometry> </local:PathIconButton.PathData> <TextBlock VerticalAlignment="Center" Text="작업 전송" /> </local:PathIconButton> <local:PathIconButton HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Padding="10" Background="#007bff" Foreground="White" MouseOverBrush="#0056b3" PressedBrush="#004085" PathWidth="20" PathHeight="20"> <local:PathIconButton.PathData> <Geometry>M 25 25 H 75 A 5 5 0 0 1 80 30 V 70 A5 5 0 0 1 75 75 H 25 A 5 5 0 0 1 20 70 V 30 A 5 5 0 0 1 25 25 Z</Geometry> </local:PathIconButton.PathData> <TextBlock VerticalAlignment="Center" Text="작업 중단" /> </local:PathIconButton> <local:PathIconButton HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Padding="10" Background="#007bff" Foreground="White" MouseOverBrush="#0056b3" PressedBrush="#004085" PathWidth="20" PathHeight="20" IsEnabled="False"> <local:PathIconButton.PathData> <Geometry>M 25 25 H 75 A 5 5 0 0 1 80 30 V 70 A5 5 0 0 1 75 75 H 25 A 5 5 0 0 1 20 70 V 30 A 5 5 0 0 1 25 25 Z</Geometry> </local:PathIconButton.PathData> <TextBlock VerticalAlignment="Center" Text="작업 중단" /> </local:PathIconButton> </StackPanel> </Window> |
TestProject.zip
■ Button 엘리먼트를 사용해 클릭시 회전하는 톱니바퀴 버튼을 만드는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <Window.Resources> <Style x:Key="GearButtonStyleKey" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Ellipse Fill="{TemplateBinding Background}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" /> <Path Name="gearPath" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Stretch="Uniform" Fill="{TemplateBinding Foreground}" RenderTransformOrigin="0.5 0.5" Data="M 495.9 166.6 c 3.2 8.7 .5 18.4 -6.4 24.6 l -43.3 39.4 c 1.1 8.3 1.7 16.8 1.7 25.4 s -0.6 17.1 -1.7 25.4 l 43.3 39.4 c 6.9 6.2 9.6 15.9 6.4 24.6 c -4.4 11.9 -9.7 23.3 -15.8 34.3 l -4.7 8.1 c -6.6 11 -14 21.4 -22.1 31.2 c -5.9 7.2 -15.7 9.6 -24.5 6.8 l -55.7 -17.7 c -13.4 10.3 -28.2 18.9 -44 25.4 l -12.5 57.1 c -2 9.1 -9 16.3 -18.2 17.8 c -13.8 2.3 -28 3.5 -42.5 3.5 s -28.7 -1.2 -42.5 -3.5 c -9.2 -1.5 -16.2 -8.7 -18.2 -17.8 l -12.5 -57.1 c -15.8 -6.5 -30.6 -15.1 -44 -25.4 L 83.1 425.9 c -8.8 2.8 -18.6 0.3 -24.5 -6.8 c -8.1 -9.8 -15.5 -20.2 -22.1 -31.2 l -4.7 -8.1 c -6.1 -11 -11.4 -22.4 -15.8 -34.3 c -3.2 -8.7 -0.5 -18.4 6.4 -24.6 l 43.3 -39.4 C 64.6 273.1 64 264.6 64 256 s 0.6 -17.1 1.7 -25.4 L 22.4 191.2 c -6.9 -6.2 -9.6 -15.9 -6.4 -24.6 c 4.4 -11.9 9.7 -23.3 15.8 -34.3 l 4.7 -8.1 c 6.6 -11 14 -21.4 22.1 -31.2 c 5.9 -7.2 15.7 -9.6 24.5 -6.8 l 55.7 17.7 c 13.4 -10.3 28.2 -18.9 44 -25.4 l 12.5 -57.1 c 2 -9.1 9 -16.3 18.2 -17.8 C 227.3 1.2 241.5 0 256 0 s 28.7 1.2 42.5 3.5 c 9.2 1.5 16.2 8.7 18.2 17.8 l 12.5 57.1 c 15.8 6.5 30.6 15.1 44 25.4 l 55.7 -17.7 c 8.8 -2.8 18.6 -0.3 24.5 6.8 c 8.1 9.8 15.5 20.2 22.1 31.2 l 4.7 8.1 c 6.1 11 11.4 22.4 15.8 34.3 z M 256 336 c 44.2 0 80 -35.8 80 -80 s -35.8 -80 -80 -80 s -80 35.8 -80 80 s 35.8 80 80 80 z"> <Path.RenderTransform> <RotateTransform x:Name="gearRotateTransform" /> </Path.RenderTransform> </Path> </Grid> <ControlTemplate.Triggers> <EventTrigger RoutedEvent="Button.PreviewMouseDown"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="gearRotateTransform" Storyboard.TargetProperty="Angle" To="180" Duration="00:00:00.1"/> </Storyboard> </BeginStoryboard> </EventTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <Button Name="gearButton1" Style="{StaticResource GearButtonStyleKey}" Width="32" Height="32" Background="Transparent" Foreground="DarkGray" /> <Button Name="gearButton2" Style="{StaticResource GearButtonStyleKey}" Margin="0 10 0 0" Width="64" Height="64" Background="Transparent" Foreground="DarkGray" /> <Button Name="gearButton3" Style="{StaticResource GearButtonStyleKey}" Margin="0 10 0 0" Width="128" Height="128" Background="Transparent" Foreground="DarkGray" /> </StackPanel> </Window> |
▶ MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace TestProject; /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 회전 여부 /// </summary> private bool isRotating = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); this.gearButton1.Click += settingButton_Click; this.gearButton2.Click += settingButton_Click; this.gearButton3.Click += settingButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 기어 버튼 클릭시 처리하기 - settingButton_Click(sender, e) /// <summary> /// 기어 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void settingButton_Click(object sender, RoutedEventArgs e) { if(!this.isRotating) { this.isRotating = true; Button button = sender as Button; Path gearPath = (Path)button.Template.FindName("gearPath", button); RotateTransform rotateTransform = gearPath.RenderTransform as RotateTransform; DoubleAnimation rotateBackAnimation = new DoubleAnimation { Duration = TimeSpan.FromSeconds(0.2), From = 180, To = 0 }; rotateBackAnimation.Completed += (s, _) => { this.isRotating = false; rotateTransform.Angle = 0; }; rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotateBackAnimation); } } #endregion } |
TestProject.zip
■ Control 클래스를 사용해 토글 스위치를 만드는 방법을 보여준다. ▶ THEMES/Generic.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ToggleSwitch}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ToggleSwitch}"> <Grid> <Border Name="PART_Switch" Width="60" Height="30" CornerRadius="15" Background="{TemplateBinding Background}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Ellipse Name="PART_Thumb" Margin="2" Width="20" Height="20" Fill="White"> <Ellipse.RenderTransform> <TranslateTransform X="0" /> </Ellipse.RenderTransform> </Ellipse> <ContentPresenter Name="PART_ContentPresenter" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </Border> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter TargetName="PART_Switch" Property="Background" Value="{Binding OnBrush, RelativeSource={RelativeSource TemplatedParent}}" /> <Setter TargetName="PART_Thumb" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="30" /> </Setter.Value> </Setter> <Setter TargetName="PART_ContentPresenter" Property="Content" Value="{Binding OnContent, RelativeSource={RelativeSource TemplatedParent}}" /> </Trigger> <Trigger Property="IsChecked" Value="False"> <Setter TargetName="PART_Switch" Property="Background" Value="{Binding OffBrush, RelativeSource={RelativeSource TemplatedParent}}" /> <Setter TargetName="PART_Thumb" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="0" /> </Setter.Value> </Setter> <Setter TargetName="PART_ContentPresenter" Property="Content" Value="{Binding OffContent, RelativeSource={RelativeSource TemplatedParent}}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ ToggleSwitch.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 토글 스위치 /// </summary> public class ToggleSwitch : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// DependencyProperty ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 체크 여부 속성 - IsCheckedProperty /// <summary> /// 체크 여부 속성 /// </summary> public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register ( "IsChecked", typeof(bool), typeof(ToggleSwitch), new PropertyMetadata(false) ); #endregion #region ON 컨텐트 속성 - OnContentProperty /// <summary> /// ON 컨텐트 속성 /// </summary> public static readonly DependencyProperty OnContentProperty = DependencyProperty.Register ( "OnContent", typeof(object), typeof(ToggleSwitch), new PropertyMetadata("ON") ); #endregion #region ON 브러시 속성 - OnBrushProperty /// <summary> /// ON 브러시 /// </summary> public static readonly DependencyProperty OnBrushProperty = DependencyProperty.Register ( "OnBrush", typeof(Brush), typeof(ToggleSwitch), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(33, 150, 243))) ); #endregion #region OFF 컨텐트 속성- OffContentProperty /// <summary> /// OFF 컨텐트 속성 /// </summary> public static readonly DependencyProperty OffContentProperty = DependencyProperty.Register ( "OffContent", typeof(object), typeof(ToggleSwitch), new PropertyMetadata("OFF") ); #endregion #region OFF 브러시 속성 - OffBrushProperty /// <summary> /// OFF 브러시 /// </summary> public static readonly DependencyProperty OffBrushProperty = DependencyProperty.Register ( "OffBrush", typeof(Brush), typeof(ToggleSwitch), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(204, 204, 204))) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 체크 여부 - IsChecked /// <summary> /// 체크 여부 /// </summary> public bool IsChecked { get { return (bool)GetValue(IsCheckedProperty); } set { SetValue(IsCheckedProperty, value); } } #endregion #region ON 컨텐트 - OnContent /// <summary> /// ON 컨텐트 /// </summary> public object OnContent { get { return GetValue(OnContentProperty); } set { SetValue(OnContentProperty, value); } } #endregion #region ON 브러시 - OnBrush /// <summary> /// ON 브러시 /// </summary> public Brush OnBrush { get { return (Brush)GetValue(OnBrushProperty); } set { SetValue(OnBrushProperty, value); } } #endregion #region OFF 컨텐트 - OffContent /// <summary> /// OFF 컨텐트 /// </summary> public object OffContent { get { return GetValue(OffContentProperty); } set { SetValue(OffContentProperty, value); } } #endregion #region OFF 브러시 - OffBrush /// <summary> /// OFF 브러시 /// </summary> public Brush OffBrush { get { return (Brush)GetValue(OffBrushProperty); } set { SetValue(OffBrushProperty, value); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ToggleSwitch() /// <summary> /// 생성자 /// </summary> static ToggleSwitch() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ToggleSwitch), new FrameworkPropertyMetadata(typeof(ToggleSwitch))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); DependencyObject dependencyObject = GetTemplateChild("PART_Switch"); if(dependencyObject is Border switchPart) { switchPart.MouseLeftButtonDown += (s, e) => { IsChecked = !IsChecked; e.Handled = true; }; } } #endregion } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal"> <TextBlock VerticalAlignment="Center" Text="배경 이미지 표시" /> <local:ToggleSwitch Margin="10 0 0 0" VerticalAlignment="Center" OnBrush="Gold" OnContent="" OffContent="" /> </StackPanel> </Window> |
TestProject.zip
■ ScrollViewer 클래스에서 수평/수직 ScrollBar 객체를 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System.Windows.Controls; using System.Windows.Controls.Primitives; #region 수직 스크롤바 구하기 - GetVerticalScrollBar(scrollViewer) /// <summary> /// 수직 스크롤바 구하기 /// </summary> /// <param name="scrollViewer">스크롤 뷰어</param> /// <returns>수직 스크롤바</returns> public ScrollBar GetVerticalScrollBar(ScrollViewer scrollViewer) { return (ScrollBar)scrollViewer.Template.FindName("PART_VerticalScrollBar", scrollViewer); } #endregion #region 수평 스크롤바 구하기 - GetHorizontalScrollBar(scrollViewer) /// <summary> /// 수평 스크롤바 구하기 /// </summary> /// <param name="scrollViewer">스크롤 뷰어</param> /// <returns>수평 스크롤바</returns> public ScrollBar GetHorizontalScrollBar(ScrollViewer scrollViewer) { return (ScrollBar)scrollViewer.Template.FindName("PART_HorizontalScrollBar", scrollViewer); } #endregion |
■ GridView 엘리먼트의 SelectionMode/IsMultiSelectCheckBoxEnabled 속성을 사용해 선택 모드가 Multiple인 경우 체크 박스를 숨기는 방법을 보여준다. ※ SelectionMode 속성이 Multiple인 경우 체크 박스가
■ GridView 엘리먼트의 ItemTemplate 속성을 사용해 항목을 표시하는 방법을 보여준다. ※ 비주얼 스튜디오에서 TestProject(Unpackaged) 모드로 빌드한다. ※ TestProject.csproj 프로젝트 파일에서 WindowsPackageType 태그를
■ ListView 엘리먼트의 ItemContainerStyle 속성을 사용해 항목 컨테이너 속성을 설정하는 방법을 보여준다. (ListViewItem 객체) ※ ListViewItem의 컨텐츠는 기본적으로 왼쪽에 맞추어진다 ※ 즉
■ ListView 엘리먼트의 ItemTemplate 속성을 사용해 항목을 표시하는 방법을 보여준다. ※ ItemTemplate 및 DisplayMemberPath를 동시에 사용할 수 없다. 두 속성을 모두 설정한