[C#/WINFORM/REOGRID/.NET8] ReoGridControl 클래스 사용하기 (단순 객체 생성)
■ ReoGridControl 클래스를 사용하는 방법을 보여준다. (단순 객체 생성) TestProject.zip
■ ReoGridControl 클래스를 사용하는 방법을 보여준다. (단순 객체 생성) TestProject.zip
■ unvell.ReoGrid.dll 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ Window 클래스에서 윈도우를 화면 왼쪽에 고정하고 나머지 영역을 작업 영역으로 설정하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 |
<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> |
▶ 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 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 |
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; namespace TestProject; /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 사각형 - RECT /// <summary> /// 사각형 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct RECT { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 왼쪽 /// </summary> public int Left; /// <summary> /// 위쭉 /// </summary> public int Top; /// <summary> /// 오른쪽 /// </summary> public int Right; /// <summary> /// 아래쪽 /// </summary> public int Bottom; #endregion } #endregion #region 모니터 정보 - MONITOR_INFORMATION /// <summary> /// 모니터 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct MONITOR_INFORMATION { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 크기 /// </summary> public uint Size; /// <summary> /// 모니터 사각형 /// </summary> public RECT MonitorRectangle; /// <summary> /// 작업 영역 사각형 /// </summary> public RECT WorkAreaRectangle; /// <summary> /// 플래그 /// </summary> public uint Flag; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 시스템 메트릭스 구하기 - GetSystemMetrics(index) /// <summary> /// 시스템 메트릭스 구하기 /// </summary> /// <param name="index">인덱스</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern int GetSystemMetrics(int index); #endregion #region 윈도우에서 모니터 구하기 - MonitorFromWindow(windowHandle, flag) /// <summary> /// 윈도우에서 모니터 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="flag">플래그</param> /// <returns>모니터 핸들</returns> [DllImport("user32")] private static extern IntPtr MonitorFromWindow(IntPtr windowHandle, uint flag); #endregion #region 모니터 정보 구하기 - GetMonitorInfo(monitorHandle, monitorInformation) /// <summary> /// 모니터 정보 구하기 /// </summary> /// <param name="monitorHandle">모니터 핸들</param> /// <param name="monitorInformation">모니터 정보</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool GetMonitorInfo(IntPtr monitorHandle, ref MONITOR_INFORMATION monitorInformation); #endregion #region 시스템 매개 변수 정보 설정하기 - SystemParametersInfo(action, parameter1, parameter2, flag) /// <summary> /// 시스템 매개 변수 정보 설정하기 /// </summary> /// <param name="action">액션</param> /// <param name="parameter1">매개 변수 1</param> /// <param name="parameter2">매개 변수 2</param> /// <param name="flag">플래그</param> /// <returns>처리 결과</returns> [DllImport("user32", SetLastError = true)] private static extern bool SystemParametersInfo(uint action, uint parameter1, IntPtr parameter2, uint flag); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SM_CXSCREEN /// </summary> private const int SM_CXSCREEN = 0; /// <summary> /// SM_CYSCREEN /// </summary> private const int SM_CYSCREEN = 1; /// <summary> /// MONITOR_DEFAULTTONEAREST /// </summary> private const uint MONITOR_DEFAULTTONEAREST = 2; /// <summary> /// SPI_SETWORKAREA /// </summary> private const uint SPI_SETWORKAREA = 0x002F; /// <summary> /// 원본 작업 영역 사각형 /// </summary> private RECT originalWorkAreaRectangle; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); Loaded += Window_Loaded; Closing += Window_Closing; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 윈도우 로드시 처리하기 - Window_Loaded(sender, e) /// <summary> /// 윈도우 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Window_Loaded(object sender, RoutedEventArgs e) { SetWindowPosition(); SetWorkArea(); SetTopMostWindow(); } #endregion #region 윈도우 닫을 경우 처리하기 - Window_Closing(sender, e) /// <summary> /// 윈도우 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Window_Closing(object sender, CancelEventArgs e) { RestoreWorkArea(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 윈도우 위치 설정하기 - SetWindowPosition() /// <summary> /// 윈도우 위치 설정하기 /// </summary> private void SetWindowPosition() { IntPtr windowHandle = new WindowInteropHelper(this).Handle; IntPtr monitorHandle = MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST); MONITOR_INFORMATION monitorInformation = new MONITOR_INFORMATION(); monitorInformation.Size = (uint)Marshal.SizeOf(typeof(MONITOR_INFORMATION)); GetMonitorInfo(monitorHandle, ref monitorInformation); RECT workAreaRectangle = monitorInformation.WorkAreaRectangle; Width = 400 + 7; Height = workAreaRectangle.Bottom - workAreaRectangle.Top + 7; Left = workAreaRectangle.Right - 400; Top = workAreaRectangle.Top; } #endregion #region 작업 영역 설정하기 - SetWorkArea() /// <summary> /// 작업 영역 설정하기 /// </summary> private void SetWorkArea() { IntPtr windowHandle = new WindowInteropHelper(this).Handle; IntPtr monitorHandle = MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST); MONITOR_INFORMATION monitorInformation = new MONITOR_INFORMATION(); monitorInformation.Size = (uint)Marshal.SizeOf(typeof(MONITOR_INFORMATION)); GetMonitorInfo(monitorHandle, ref monitorInformation); this.originalWorkAreaRectangle = monitorInformation.WorkAreaRectangle; RECT workAreaRectangle = monitorInformation.WorkAreaRectangle; workAreaRectangle.Right -= (int)Width; IntPtr workAreaRectangleHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(RECT))); Marshal.StructureToPtr(workAreaRectangle, workAreaRectangleHandle, false); SystemParametersInfo(SPI_SETWORKAREA, 0, workAreaRectangleHandle, 0); Marshal.FreeHGlobal(workAreaRectangleHandle); } #endregion #region 작업 영역 복원하기 - RestoreWorkArea() /// <summary> /// 작업 영역 복원하기 /// </summary> private void RestoreWorkArea() { IntPtr workAreaRectangleHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(RECT))); Marshal.StructureToPtr(originalWorkAreaRectangle, workAreaRectangleHandle, false); SystemParametersInfo(SPI_SETWORKAREA, 0, workAreaRectangleHandle, 0); Marshal.FreeHGlobal(workAreaRectangleHandle); } #endregion #region 최상위 윈도우 설정하기 - SetTopMostWindow() /// <summary> /// 최상위 윈도우 설정하기 /// </summary> private void SetTopMostWindow() { Topmost = true; } #endregion } |
TestProject.zip
■ Window 클래스에서 윈도우를 화면 앞으로 가져오는 방법을 보여준다. ▶ WindowHelper.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 |
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; /// <summary> /// 윈도우 헬퍼 /// </summary> public static class WindowHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 활성 윈도우 설정하기 - SetForegroundWindow(windowHandle) /// <summary> /// 활성 윈도우 설정하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr windowHandle); #endregion #region 윈도우 표시하기 - ShowWindow(windowHandle, command) /// <summary> /// 윈도우 표시하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="commandShow">명령</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool ShowWindow(IntPtr windowHandle, int command); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SW_SHOW /// </summary> private const int SW_SHOW = 5; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 앞으로 가져오기 - BringToFront(window) /// <summary> /// 윈도우 앞으로 가져오기 /// </summary> /// <param name="window">윈도우</param> public static void BringToFront(Window window) { WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window); nint windowHandle = windowInteropHelper.Handle; ShowWindow(windowHandle, SW_SHOW); SetForegroundWindow(windowHandle); } #endregion } |
■ Win32Window 클래스의 isMinimized 속성과 restore/activate 메소드를 사용해 윈도우를 전면으로 가져오는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 |
import pygetwindow as gw import time def bringWindowToFront(win32Window): if win32Window.isMinimized: win32Window.restore() win32Window.activate() time.sleep(0.5) # 창이 완전히 활성화될 때까지 대기한다. |
※ pip install pygetwindow
■ getWindowsWithTitle 함수를 사용해 크롬 브라우저 윈도우를 구하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 |
import pygetwindow as gw def findChromeWindow(): win32WindowList = gw.getWindowsWithTitle("Chrome") if win32WindowList: return win32WindowList[0] else: raise Exception("실행 중인 크롬 브라우저를 찾을 수 없습니다.") |
※ pip install pygetwindow 명령을 실행했다.
■ 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 23 24 25 |
<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:ZoomableCanvas}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ZoomableCanvas}"> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <Canvas Name="PART_Canvas" Width="{TemplateBinding CanvasWidth}" Height="{TemplateBinding CanvasHeight}" Background="LightGray"> </Canvas> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ 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="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 |
<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:ZoomableCanvas Margin="10" Background="LightYellow" CanvasWidth="500" CanvasHeight="400" ClipToBounds="True" /> </Window> |
▶ ZoomableCanvas.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 |
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace TestProject; /// <summary> /// 확대/축소 컨트롤 /// </summary> public class ZoomableCanvas : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 캔버스 너비 속성 - CanvasWidthProperty /// <summary> /// 캔버스 너비 속성 /// </summary> public static readonly DependencyProperty CanvasWidthProperty = DependencyProperty.Register ( "CanvasWidth", typeof(double), typeof(ZoomableCanvas), new PropertyMetadata(300.0, CanvasSizePropertyChangedCallback) ); #endregion #region 캔버스 높이 속성 - CanvasHeightProperty /// <summary> /// 캔버스 높이 속성 /// </summary> public static readonly DependencyProperty CanvasHeightProperty = DependencyProperty.Register ( "CanvasHeight", typeof(double), typeof(ZoomableCanvas), new PropertyMetadata(200.0, CanvasSizePropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 캔버스 너비 - CanvasWidth /// <summary> /// 캔버스 너비 /// </summary> public double CanvasWidth { get => (double)GetValue(CanvasWidthProperty); set => SetValue(CanvasWidthProperty, value); } #endregion #region 캔버스 높이 - CanvasHeight /// <summary> /// 캔버스 높이 /// </summary> public double CanvasHeight { get => (double)GetValue(CanvasHeightProperty); set => SetValue(CanvasHeightProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 캔버스 /// </summary> private Canvas canvas; /// <summary> /// 스케일 변환 /// </summary> private ScaleTransform scaleTransform; /// <summary> /// 이동 변환 /// </summary> private TranslateTransform translateTransform; /// <summary> /// 시작 포인트 /// </summary> private Point startPoint; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ZoomableCanvas() /// <summary> /// 생성자 /// </summary> static ZoomableCanvas() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ZoomableCanvas), new FrameworkPropertyMetadata(typeof(ZoomableCanvas))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 캔버스 크기 속성 변경시 콜백 처리하기 - CanvasSizePropertyChangedCallback(d, e) /// <summary> /// 캔버스 크기 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void CanvasSizePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ZoomableCanvas zoomableCanvas = d as ZoomableCanvas; if(zoomableCanvas != null && zoomableCanvas.canvas != null) { zoomableCanvas.canvas.Width = zoomableCanvas.CanvasWidth; zoomableCanvas.canvas.Height = zoomableCanvas.CanvasHeight; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.canvas = GetTemplateChild("PART_Canvas") as Canvas; if(this.canvas != null) { this.scaleTransform = new ScaleTransform(); this.translateTransform = new TranslateTransform(); TransformGroup transformGroup = new TransformGroup(); transformGroup.Children.Add(this.scaleTransform ); transformGroup.Children.Add(this.translateTransform); this.canvas.RenderTransformOrigin = new Point(0.5, 0.5); this.canvas.RenderTransform = transformGroup; } } #endregion //////////////////////////////////////////////////////////////////////////////// Protected #region 마우스 휠 처리하기 - OnMouseWheel(e) /// <summary> /// 마우스 휠 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseWheel(MouseWheelEventArgs e) { base.OnMouseWheel(e); if(this.canvas == null) { return; } double zoom = e.Delta > 0 ? 1.1 : 0.9; Point mousePoition = e.GetPosition(this.canvas); this.scaleTransform.ScaleX *= zoom; this.scaleTransform.ScaleY *= zoom; this.translateTransform.X += (1 - zoom) * mousePoition.X; this.translateTransform.Y += (1 - zoom) * mousePoition.Y; } #endregion #region 마우스 왼쪽 버튼 DOWN 처리하기 - OnMouseLeftButtonDown(e) /// <summary> /// 마우스 왼쪽 버튼 DOWN 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); this.startPoint = e.GetPosition(this); CaptureMouse(); } #endregion #region 마우스 이동시 처리하기 - OnMouseMove(e) /// <summary> /// 마우스 이동시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if(IsMouseCaptured) { Point currentPoint = e.GetPosition(this); Vector deltaVector = currentPoint - this.startPoint; this.translateTransform.X += deltaVector.X; this.translateTransform.Y += deltaVector.Y; this.startPoint = currentPoint; } } #endregion #region 마우스 왼쪽 버튼 UP 처리하기 - OnMouseLeftButtonUp(e) /// <summary> /// 마우스 왼쪽 버튼 UP 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { base.OnMouseLeftButtonUp(e); ReleaseMouseCapture(); } #endregion } |
TestProject.zip
■ 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 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 |
<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:ProcessRing}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ProcessRing}"> <Grid Background="{TemplateBinding Background}"> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding RingWidth}" Height="{TemplateBinding RingHeight}"> <Grid Name="PART_ContainerGrid"> <Path Name="PART_BackgroundRingPath" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{TemplateBinding RingThickness}" Stroke="{TemplateBinding RingBrush}" Opacity="0.3"> <Path.Data> <PathGeometry> <PathFigure x:Name="PART_BackgroundPathFigure"> <ArcSegment x:Name="PART_BackgroundArcSegment" Point="50 0" Size="50 50" SweepDirection="Clockwise" /> </PathFigure> </PathGeometry> </Path.Data> </Path> <Path Name="PART_RingPath" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{TemplateBinding RingThickness}" Stroke="{TemplateBinding RingBrush}" RenderTransformOrigin="0.5 0.5"> <Path.Data> <PathGeometry> <PathFigure x:Name="PART_PathFigure"> <ArcSegment x:Name="PART_ArcSegment" Point="50 0" Size="50 50" SweepDirection="Clockwise" /> </PathFigure> </PathGeometry> </Path.Data> <Path.RenderTransform> <RotateTransform x:Name="PART_RotationTransform" /> </Path.RenderTransform> </Path> </Grid> </Viewbox> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ 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="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 |
<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:ProcessRing Width="150" Height="150" RingWidth="100" RingHeight="100" RingStartAngle="0" RingEndAngle="270" RingThickness="10" RingBrush="Blue" IsProcessing="True" /> </Window> |
▶ ProcessRing.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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 |
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 class ProcessRing : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 속성 - RingWidthProperty /// <summary> /// 링 너비 속성 /// </summary> public static readonly DependencyProperty RingWidthProperty = DependencyProperty.Register ( "RingWidth", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 높이 속성 - RingHeightProperty /// <summary> /// 링 높이 속성 /// </summary> public static readonly DependencyProperty RingHeightProperty = DependencyProperty.Register ( "RingHeight", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 시작 각도 속성 - RingStartAngleProperty /// <summary> /// 링 시작 각도 속성 /// </summary> public static readonly DependencyProperty RingStartAngleProperty = DependencyProperty.Register ( "RingStartAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(0.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 종료 각도 속성 - RingEndAngleProperty /// <summary> /// 링 종료 각도 속성 /// </summary> public static readonly DependencyProperty RingEndAngleProperty = DependencyProperty.Register ( "RingEndAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(360.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 두께 속성 - RingThicknessProperty /// <summary> /// 링 두께 속성 /// </summary> public static readonly DependencyProperty RingThicknessProperty = DependencyProperty.Register ( "RingThickness", typeof(double), typeof(ProcessRing), new PropertyMetadata(5.0, RingThicknessPropertyChangedCallback) ); #endregion #region 링 브러시 속성 - RingBrushProperty /// <summary> /// 링 브러시 속성 /// </summary> public static readonly DependencyProperty RingBrushProperty = DependencyProperty.Register ( "RingBrush", typeof(Brush), typeof(ProcessRing), new PropertyMetadata(Brushes.Black) ); #endregion #region 처리 여부 속성 - IsProcessingProperty /// <summary> /// 처리 여부 속성 /// </summary> public static readonly DependencyProperty IsProcessingProperty = DependencyProperty.Register ( "IsProcessing", typeof(bool), typeof(ProcessRing), new PropertyMetadata(false, IsProcessingPropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 회전 변환 /// </summary> private RotateTransform rotateTransform; /// <summary> /// 링 패스 /// </summary> private Path ringPath; /// <summary> /// 패스 피규어 /// </summary> private PathFigure pathFigure; /// <summary> /// 아크 세그먼트 /// </summary> private ArcSegment arcSegment; /// <summary> /// 배경 링 패스 /// </summary> private Path backgroundRingPath; /// <summary> /// 배경 패스 피규어 /// </summary> private PathFigure backgroundPathFigure; /// <summary> /// 배경 아크 세그먼트 /// </summary> private ArcSegment backgroundArcSegment; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 - RingWidth /// <summary> /// 링 너비 /// </summary> public double RingWidth { get => (double)GetValue(RingWidthProperty); set => SetValue(RingWidthProperty, value); } #endregion #region 링 높이 - RingHeight /// <summary> /// 링 높이 /// </summary> public double RingHeight { get => (double)GetValue(RingHeightProperty); set => SetValue(RingHeightProperty, value); } #endregion #region 링 시작 각도 - RingStartAngle /// <summary> /// 링 시작 각도 /// </summary> public double RingStartAngle { get => (double)GetValue(RingStartAngleProperty); set => SetValue(RingStartAngleProperty, value); } #endregion #region 링 종료 각도 - RingEndAngle /// <summary> /// 링 종료 각도 /// </summary> public double RingEndAngle { get => (double)GetValue(RingEndAngleProperty); set => SetValue(RingEndAngleProperty, value); } #endregion #region 링 두께 - RingThickness /// <summary> /// 링 두께 /// </summary> public double RingThickness { get => (double)GetValue(RingThicknessProperty); set => SetValue(RingThicknessProperty, value); } #endregion #region 링 브러시 - RingBrush /// <summary> /// 링 브러시 /// </summary> public Brush RingBrush { get => (Brush)GetValue(RingBrushProperty); set => SetValue(RingBrushProperty, value); } #endregion #region 처리 여부 - IsProcessing /// <summary> /// 처리 여부 /// </summary> public bool IsProcessing { get => (bool)GetValue(IsProcessingProperty); set => SetValue(IsProcessingProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> static ProcessRing() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ProcessRing), new FrameworkPropertyMetadata(typeof(ProcessRing))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> public ProcessRing() { Width = 100; Height = 100; RingWidth = 80; RingHeight = 80; RingThickness = 5; Background = Brushes.Transparent; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 링 각도 속성 변경시 콜백 처리하기 - RingAnglePropertyChangedCallback(d, e) /// <summary> /// 링 각도 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingAnglePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateRing(); } #endregion #region 링 두께 속성 변경시 콜백 처리하기 - RingThicknessPropertyChangedCallback(d, e) /// <summary> /// 링 두께 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingThicknessPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.RingThickness = Math.Min((double)e.NewValue, Math.Min(processRing.RingWidth, processRing.RingHeight) / 2); processRing.UpdateRing(); } #endregion #region 처리 여부 속성 변경시 콜백 처리하기 - IsProcessingPropertyChangedCallback(d, e) /// <summary> /// 처리 여부 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void IsProcessingPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateAnimation(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.rotateTransform = GetTemplateChild("PART_RotationTransform" ) as RotateTransform; this.ringPath = GetTemplateChild("PART_RingPath" ) as Path; this.pathFigure = GetTemplateChild("PART_PathFigure" ) as PathFigure; this.arcSegment = GetTemplateChild("PART_ArcSegment" ) as ArcSegment; this.backgroundRingPath = GetTemplateChild("PART_BackgroundRingPath" ) as Path; this.backgroundPathFigure = GetTemplateChild("PART_BackgroundPathFigure") as PathFigure; this.backgroundArcSegment = GetTemplateChild("PART_BackgroundArcSegment") as ArcSegment; UpdateRing(); UpdateAnimation(); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 포인트 회전하기 - RotatePoint(point, angle) /// <summary> /// 포인트 회전하기 /// </summary> /// <param name="point">포인트</param> /// <param name="angle">각도</param> /// <returns>회전 포인트</returns> private Point RotatePoint(Point point, double angle) { double radians = angle * (Math.PI / 180); return new Point ( point.X * Math.Cos(radians) - point.Y * Math.Sin(radians) + RingThickness / 2, point.X * Math.Sin(radians) + point.Y * Math.Cos(radians) + RingThickness / 2 ); } #endregion #region 링 업데이트하기 - UpdateRing() /// <summary> /// 링 업데이트하기 /// </summary> private void UpdateRing() { if(this.pathFigure != null && this.arcSegment != null) { double radius = Math.Min(RingWidth, RingHeight) / 2 - RingThickness / 2; double angleDifference = (RingEndAngle - RingStartAngle + 360) % 360; #region 링를 설정한다. Point startPoint = new(radius, 0); startPoint = RotatePoint(startPoint, RingStartAngle); this.pathFigure.StartPoint = new Point(startPoint.X + radius, startPoint.Y + radius); Point endPoint = new Point(radius, 0); endPoint = RotatePoint(endPoint, RingEndAngle); this.arcSegment.Point = new Point(endPoint.X + radius, endPoint.Y + radius); this.arcSegment.Size = new Size(radius, radius); this.arcSegment.IsLargeArc = angleDifference > 180; #endregion #region 배경 링를 설정한다. Point backgroundStartPoint = new(radius, 0d); backgroundStartPoint = RotatePoint(backgroundStartPoint, 0d); this.backgroundPathFigure.StartPoint = new Point(backgroundStartPoint.X + radius, backgroundStartPoint.Y + radius); Point backgroundEndPoint = new Point(radius, 0); backgroundEndPoint = RotatePoint(backgroundEndPoint, 359.9); this.backgroundArcSegment.Point = new Point(backgroundEndPoint.X + radius, backgroundEndPoint.Y + radius); this.backgroundArcSegment.Size = new Size(radius, radius); this.backgroundArcSegment.IsLargeArc = angleDifference > 180; #endregion } } #endregion #region 애니메이션 업데이트하기 - UpdateAnimation() /// <summary> /// 애니메이션 업데이트하기 /// </summary> private void UpdateAnimation() { if(this.rotateTransform != null && this.ringPath != null) { if(IsProcessing) { DoubleAnimation rotateAnimation = new() { RepeatBehavior = RepeatBehavior.Forever, Duration = TimeSpan.FromSeconds(2), From = 0, To = 360 }; this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation); } else { this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null); } } } #endregion } |
■ 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 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<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:ProcessRing}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ProcessRing}"> <Grid Background="{TemplateBinding Background}"> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding RingWidth}" Height="{TemplateBinding RingHeight}"> <Grid Name="PART_ContainerGrid" RenderTransformOrigin="0.5 0.5"> <Grid.RenderTransform> <RotateTransform x:Name="PART_RotationTransform" /> </Grid.RenderTransform> <Path Name="PART_RingPath" StrokeThickness="{TemplateBinding RingThickness}" Stroke="{TemplateBinding RingBrush}"> <Path.Data> <PathGeometry> <PathFigure x:Name="PART_PathFigure"> <ArcSegment x:Name="PART_ArcSegment" Point="50 0" Size="50 50" SweepDirection="Clockwise" /> </PathFigure> </PathGeometry> </Path.Data> </Path> </Grid> </Viewbox> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ 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="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 |
<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:ProcessRing Width="150" Height="150" RingWidth="100" RingHeight="100" RingStartAngle="0" RingEndAngle="330" RingThickness="10" RingBrush="Gold" IsProcessing="True" /> </Window> |
▶ ProcessRing.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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
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 class ProcessRing : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 속성 - RingWidthProperty /// <summary> /// 링 너비 속성 /// </summary> public static readonly DependencyProperty RingWidthProperty = DependencyProperty.Register ( "RingWidth", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 높이 속성 - RingHeightProperty /// <summary> /// 링 높이 속성 /// </summary> public static readonly DependencyProperty RingHeightProperty = DependencyProperty.Register ( "RingHeight", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 시작 각도 속성 - RingStartAngleProperty /// <summary> /// 링 시작 각도 속성 /// </summary> public static readonly DependencyProperty RingStartAngleProperty = DependencyProperty.Register ( "RingStartAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(0.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 종료 각도 속성 - RingEndAngleProperty /// <summary> /// 링 종료 각도 속성 /// </summary> public static readonly DependencyProperty RingEndAngleProperty = DependencyProperty.Register ( "RingEndAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(360.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 두께 속성 - RingThicknessProperty /// <summary> /// 링 두께 속성 /// </summary> public static readonly DependencyProperty RingThicknessProperty = DependencyProperty.Register ( "RingThickness", typeof(double), typeof(ProcessRing), new PropertyMetadata(5.0, RingThicknessPropertyChangedCallback) ); #endregion #region 링 브러시 속성 - RingBrushProperty /// <summary> /// 링 브러시 속성 /// </summary> public static readonly DependencyProperty RingBrushProperty = DependencyProperty.Register ( "RingBrush", typeof(Brush), typeof(ProcessRing), new PropertyMetadata(Brushes.Black) ); #endregion #region 처리 여부 속성 - IsProcessingProperty /// <summary> /// 처리 여부 속성 /// </summary> public static readonly DependencyProperty IsProcessingProperty = DependencyProperty.Register ( "IsProcessing", typeof(bool), typeof(ProcessRing), new PropertyMetadata(false, IsProcessingPropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 회전 변환 /// </summary> private RotateTransform rotateTransform; /// <summary> /// 링 패스 /// </summary> private Path ringPath; /// <summary> /// 패스 피규어 /// </summary> private PathFigure pathFigure; /// <summary> /// 아크 세그먼트 /// </summary> private ArcSegment arcSegment; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 - RingWidth /// <summary> /// 링 너비 /// </summary> public double RingWidth { get => (double)GetValue(RingWidthProperty); set => SetValue(RingWidthProperty, value); } #endregion #region 링 높이 - RingHeight /// <summary> /// 링 높이 /// </summary> public double RingHeight { get => (double)GetValue(RingHeightProperty); set => SetValue(RingHeightProperty, value); } #endregion #region 링 시작 각도 - RingStartAngle /// <summary> /// 링 시작 각도 /// </summary> public double RingStartAngle { get => (double)GetValue(RingStartAngleProperty); set => SetValue(RingStartAngleProperty, value); } #endregion #region 링 종료 각도 - RingEndAngle /// <summary> /// 링 종료 각도 /// </summary> public double RingEndAngle { get => (double)GetValue(RingEndAngleProperty); set => SetValue(RingEndAngleProperty, value); } #endregion #region 링 두께 - RingThickness /// <summary> /// 링 두께 /// </summary> public double RingThickness { get => (double)GetValue(RingThicknessProperty); set => SetValue(RingThicknessProperty, value); } #endregion #region 링 브러시 - RingBrush /// <summary> /// 링 브러시 /// </summary> public Brush RingBrush { get => (Brush)GetValue(RingBrushProperty); set => SetValue(RingBrushProperty, value); } #endregion #region 처리 여부 - IsProcessing /// <summary> /// 처리 여부 /// </summary> public bool IsProcessing { get => (bool)GetValue(IsProcessingProperty); set => SetValue(IsProcessingProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> static ProcessRing() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ProcessRing), new FrameworkPropertyMetadata(typeof(ProcessRing))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> public ProcessRing() { Width = 100; Height = 100; RingWidth = 80; RingHeight = 80; RingThickness = 5; Background = Brushes.Transparent; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 링 각도 속성 변경시 콜백 처리하기 - RingAnglePropertyChangedCallback(d, e) /// <summary> /// 링 각도 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingAnglePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateRing(); } #endregion #region 링 두께 속성 변경시 콜백 처리하기 - RingThicknessPropertyChangedCallback(d, e) /// <summary> /// 링 두께 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingThicknessPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.RingThickness = Math.Min((double)e.NewValue, Math.Min(processRing.RingWidth, processRing.RingHeight) / 2); processRing.UpdateRing(); } #endregion #region 처리 여부 속성 변경시 콜백 처리하기 - IsProcessingPropertyChangedCallback(d, e) /// <summary> /// 처리 여부 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void IsProcessingPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateAnimation(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.rotateTransform = GetTemplateChild("PART_RotationTransform") as RotateTransform; this.ringPath = GetTemplateChild("PART_RingPath" ) as Path; this.pathFigure = GetTemplateChild("PART_PathFigure" ) as PathFigure; this.arcSegment = GetTemplateChild("PART_ArcSegment" ) as ArcSegment; UpdateRing(); UpdateAnimation(); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 포인트 회전하기 - RotatePoint(point, angle) /// <summary> /// 포인트 회전하기 /// </summary> /// <param name="point">포인트</param> /// <param name="angle">각도</param> /// <returns>회전 포인트</returns> private Point RotatePoint(Point point, double angle) { double radians = angle * (Math.PI / 180); return new Point ( point.X * Math.Cos(radians) - point.Y * Math.Sin(radians) + RingThickness / 2, point.X * Math.Sin(radians) + point.Y * Math.Cos(radians) + RingThickness / 2 ); } #endregion #region 링 업데이트하기 - UpdateRing() /// <summary> /// 링 업데이트하기 /// </summary> private void UpdateRing() { if(this.pathFigure != null && this.arcSegment != null) { double radius = Math.Min(RingWidth, RingHeight) / 2 - RingThickness / 2; Point startPoint = new(radius, 0); startPoint = RotatePoint(startPoint, RingStartAngle); this.pathFigure.StartPoint = new Point(startPoint.X + radius, startPoint.Y + radius); Point endPoint = new Point(radius, 0); endPoint = RotatePoint(endPoint, RingEndAngle); this.arcSegment.Point = new Point(endPoint.X + radius, endPoint.Y + radius); this.arcSegment.Size = new Size(radius, radius); double angleDifference = (RingEndAngle - RingStartAngle + 360) % 360; this.arcSegment.IsLargeArc = angleDifference > 180; } } #endregion #region 애니메이션 업데이트하기 - UpdateAnimation() /// <summary> /// 애니메이션 업데이트하기 /// </summary> private void UpdateAnimation() { if(this.rotateTransform != null && this.ringPath != null) { if(IsProcessing) { DoubleAnimation rotateAnimation = new() { RepeatBehavior = RepeatBehavior.Forever, Duration = TimeSpan.FromSeconds(2), From = 0, To = 360 }; this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation); } else { this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null); } } } #endregion } |
■ 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
■ UserControl 클래스를 사용해 등고선 차트 컨트롤을 만드는 방법을 보여준다. ▶ ContourChartControl.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 |
using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace TestProject; /// <summary> /// 등고선 차트 컨트롤 /// </summary> public partial class ContourChartControl : UserControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 레벨 배열 /// </summary> private float[] levelArray; /// <summary> /// 색상 배열 /// </summary> private Color[] colorArray; /// <summary> /// 데이터 배열 /// </summary> private float[,] valueArray; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ContourChartControl() /// <summary> /// 생성자 /// </summary> public ContourChartControl() { InitializeComponent(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 데이터 설정하기 - SetData(levelArray, colorArray, valueArray) /// <summary> /// 데이터 설정하기 /// </summary> /// <param name="levelArray">레벨 배열</param> /// <param name="colorArray">색상 배열</param> /// <param name="valueArray">값 배열</param> public void SetData(float[] levelArray, Color[] colorArray, float[,] valueArray) { this.levelArray = levelArray; this.colorArray = colorArray; this.valueArray = valueArray; Invalidate(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페인트 처리하기 - OnPaint(e) /// <summary> /// 페인트 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if(this.valueArray == null || this.levelArray == null || this.colorArray == null) { return; } DrawContour(e.Graphics); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 포인트 스케일 설정하기 - ScalePoint(sourcePoint) /// <summary> /// 포인트 스케일 설정하기 /// </summary> /// <param name="sourcePoint">소스 포인트</param> /// <returns>스케일 포인트</returns> private PointF ScalePoint(PointF sourcePoint) { return new PointF(sourcePoint.X * Width / (valueArray.GetLength(0) - 1), Height - sourcePoint.Y * Height / (valueArray.GetLength(1) - 1)); } #endregion #region 등고선 셀 그리기 - DrawContourCell(graphics, x, y, valueArray, lowLevel, highLevel, color) /// <summary> /// 등고선 셀 그리기 /// </summary> /// <param name="graphics">그래픽스</param> /// <param name="x">X</param> /// <param name="y">Y</param> /// <param name="valueArray">값 배열</param> /// <param name="lowLevel">하한 레벨</param> /// <param name="highLevel">상한 레벨</param> /// <param name="color">색상</param> private void DrawContourCell(Graphics graphics, int x, int y, float[] valueArray, float lowLevel, float highLevel, Color color) { List<PointF> pointList = new List<PointF>(); for(int i = 0; i < 4; i++) { int j = (i + 1) % 4; if((valueArray[i] < lowLevel && valueArray[j] >= lowLevel) || (valueArray[i] >= lowLevel && valueArray[j] < lowLevel)) { float t = (lowLevel - valueArray[i]) / (valueArray[j] - valueArray[i]); pointList.Add ( new PointF ( x + (i % 2) + t * ((j % 2) - (i % 2)), y + (i / 2) + t * ((j / 2) - (i / 2)) ) ); } } if(pointList.Count == 2) { using(Pen pen = new Pen(color, 1)) { graphics.DrawLine(pen, ScalePoint(pointList[0]), ScalePoint(pointList[1])); } } } #endregion #region 등고선 그리기 - DrawContour(graphics) /// <summary> /// 등고선 그리기 /// </summary> /// <param name="graphics">그래픽스</param> private void DrawContour(Graphics graphics) { int width = this.valueArray.GetLength(0); int height = this.valueArray.GetLength(1); for(int x = 0; x < width - 1; x++) { for(int y = 0; y < height - 1; y++) { float[] cellValueArray = new float[] { valueArray[x , y ], valueArray[x + 1, y ], valueArray[x + 1, y + 1], valueArray[x , y + 1] }; for(int i = 0; i < this.levelArray.Length - 1; i++) { DrawContourCell(graphics, x, y, cellValueArray, this.levelArray[i], this.levelArray[i + 1], this.colorArray[i]); } } } } #endregion } |
▶ MainForm.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 |
using System; using System.Drawing; using System.Windows.Forms; namespace TestProject; /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); float[] levelArray = { 0f, 0.2f, 0.4f, 0.6f, 0.8f, 1f }; Color[] colorArray = { Color.Blue, Color.Green, Color.Yellow, Color.Orange, Color.Red }; float[,] valueArray = GetValueArray(); contourChartControl.SetData(levelArray, colorArray, valueArray); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 값 배열 구하기 - GetValueArray() /// <summary> /// 값 배열 구하기 /// </summary> /// <returns>값 배열</returns> public float[,] GetValueArray() { int width = this.contourChartControl.Width; int height = this.contourChartControl.Height; float[,] valueArray = new float[width, height]; for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { float xNormalized = (float)x / width * 10; float yNormalized = (float)y / height * 10; valueArray[x, y] = (float)(Math.Sin(xNormalized) * Math.Cos(yNormalized) + Math.Cos(xNormalized * 0.5f) * Math.Sin(yNormalized * 0.5f)); valueArray[x, y] = (valueArray[x, y] + 1) / 2; } } return valueArray; } #endregion } |
TestProject.zip
■ UserControl 클래스를 사용해 알림 메시지 컨트롤을 만드는 방법을 보여준다. ▶ NotificationControl.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 |
<UserControl x:Class="TestProject.NotificationControl" Name="userControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" BorderThickness="0" BorderBrush="Transparent" Background="Transparent"> <Border Name="border" CornerRadius="10" BorderThickness="{Binding ElementName=userControl, Path=BorderThickness}" BorderBrush="{Binding ElementName=userControl, Path=BorderBrush}" Padding="10" Background="{Binding ElementName=userControl, Path=Background}" Opacity="0"> <Border.Triggers> <EventTrigger RoutedEvent="Border.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="00:00:00.5" From="0" To="1" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Border.Triggers> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <TextBlock Name="textBlock" Grid.Column="0" VerticalAlignment="Center" TextWrapping="Wrap" Background="Transparent" Foreground="{Binding ElementName=userControl, Path=Foreground}" /> <Button Name="closeButton" Grid.Column="1" VerticalAlignment="Top" Margin="10 0 0 0" Padding="5" Content="X" /> </Grid> </Border> </UserControl> |
▶ NotificationControl.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 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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; namespace TestProject; /// <summary> /// 알림 컨트롤 /// </summary> public partial class NotificationControl : UserControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 닫은 경우 - Closed /// <summary> /// 닫은 경우 /// </summary> public event EventHandler Closed; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 테두리 두께 속성 - BorderThicknessProperty /// <summary> /// 테두리 두께 속성 /// </summary> public static new readonly DependencyProperty BorderThicknessProperty = DependencyProperty.Register ( "BorderThickness", typeof(Thickness), typeof(NotificationControl), new PropertyMetadata(new Thickness(0), BorderThicknessPropertyChangedCallback) ); #endregion #region 테두리 브러시 속성 - BorderBrushProperty /// <summary> /// 테두리 브러시 속성 /// </summary> public static new readonly DependencyProperty BorderBrushProperty = DependencyProperty.Register ( "BorderBrush", typeof(Brush), typeof(NotificationControl), new PropertyMetadata(Brushes.Blue, BorderBrushPropertyChangedCallback) ); #endregion #region 배경 브러시 - BackgroundProperty /// <summary> /// 배경 브러시 /// </summary> public static new readonly DependencyProperty BackgroundProperty = DependencyProperty.Register ( "Background", typeof(Brush), typeof(NotificationControl), new PropertyMetadata(Brushes.LightBlue, BackgroundPropertyChangedCallback) ); #endregion #region 메시지 속성 - MessageProperty /// <summary> /// 메시지 속성 /// </summary> public static readonly DependencyProperty MessageProperty = DependencyProperty.Register ( "Message", typeof(string), typeof(NotificationControl), new PropertyMetadata(string.Empty, MessagePropertyChangedCallback) ); #endregion #region 표시 시간 속성 - DisplayTimeProperty /// <summary> /// 표시 시간 속성 /// </summary> public static readonly DependencyProperty DisplayTimeProperty = DependencyProperty.Register ( "DisplayTime", typeof(TimeSpan), typeof(NotificationControl), new PropertyMetadata(TimeSpan.FromSeconds(5)) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 테두리 두께 - BorderThickness /// <summary> /// 테두리 두께 /// </summary> public new Thickness BorderThickness { get { return (Thickness)GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } #endregion #region 테두리 브러시 - BorderBrush /// <summary> /// 테두리 브러시 /// </summary> public new Brush BorderBrush { get { return (Brush)GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } #endregion #region 배경 브러시 - Background /// <summary> /// 배경 브러시 /// </summary> public new Brush Background { get { return (Brush)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } #endregion #region 메시지 - Message /// <summary> /// 메시지 /// </summary> public string Message { get { return (string)GetValue(MessageProperty); } set { SetValue(MessageProperty, value); } } #endregion #region 표시 시간 - DisplayTime /// <summary> /// 표시 시간 /// </summary> public TimeSpan DisplayTime { get { return (TimeSpan)GetValue(DisplayTimeProperty); } set { SetValue(DisplayTimeProperty, value); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - NotificationControl() /// <summary> /// 생성자 /// </summary> public NotificationControl() { InitializeComponent(); Loaded += UserControl_Loaded; this.closeButton.Click += closeButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 테두리 두께 속성 변경시 콜백 처리하기 - BorderThicknessPropertyChangedCallback(d, e) /// <summary> /// 테두리 두께 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void BorderThicknessPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { NotificationControl control = (NotificationControl)d; control.border.BorderThickness = (Thickness)e.NewValue; } #endregion #region 테두리 브러시 속성 변경시 콜백 처리하기 - BorderBrushPropertyChangedCallback(d, e) /// <summary> /// 테두리 브러시 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void BorderBrushPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { NotificationControl control = (NotificationControl)d; control.border.BorderBrush = (Brush)e.NewValue; } #endregion #region 배경 브러시 속성 변경시 콜백 처리하기 - BackgroundPropertyChangedCallback(d, e) /// <summary> /// 배경 브러시 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void BackgroundPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { NotificationControl control = (NotificationControl)d; control.border.Background = (Brush)e.NewValue; } #endregion #region 메시지 속성 변경시 콜백 처리하기 - MessagePropertyChangedCallback(d, e) /// <summary> /// 메시지 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void MessagePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { NotificationControl control = (NotificationControl)d; control.textBlock.Text = (string)e.NewValue; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private ////////////////////////////////////////////////////////////////////// Event #region 사용자 컨트롤 로드시 처리하기 - UserControl_Loaded(sender, e) /// <summary> /// 사용자 컨트롤 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void UserControl_Loaded(object sender, RoutedEventArgs e) { StartCloseTimer(); } #endregion #region 닫기 버튼 클릭시 처리하기 - closeButton_Click(sender, e) /// <summary> /// 닫기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void closeButton_Click(object sender, RoutedEventArgs e) { Close(); } #endregion #region 페이드 아웃 애니메이션 완료시 처리하기 - fadeOutAnimation_Completed(sender, e) /// <summary> /// 페이드 아웃 애니메이션 완료시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void fadeOutAnimation_Completed(object sender, EventArgs e) { Panel parentPanel = Parent as Panel; parentPanel?.Children.Remove(this); Closed?.Invoke(this, EventArgs.Empty); } #endregion ////////////////////////////////////////////////////////////////////// Function #region 닫기 - Close() /// <summary> /// 닫기 /// </summary> private void Close() { DoubleAnimation fadeOutAnimation = new DoubleAnimation { From = 1, To = 0, Duration = new Duration(TimeSpan.FromSeconds(0.5)) }; fadeOutAnimation.Completed += fadeOutAnimation_Completed; BeginAnimation(OpacityProperty, fadeOutAnimation); } #endregion #region 닫기 타이머 시작하기 - StartCloseTimer() /// <summary> /// 닫기 타이머 시작하기 /// </summary> private void StartCloseTimer() { DispatcherTimer timer = new DispatcherTimer(); timer.Tick += (s, e) => Close(); timer.Interval = DisplayTime; timer.Start(); } #endregion } |
▶ NotificationHelper.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 |
using System; using System.Collections.Generic; using System.Windows.Controls; namespace TestProject; /// <summary> /// 알림 헬퍼 /// </summary> public class NotificationHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 알림 컨트롤 큐 /// </summary> private readonly Queue<NotificationControl> notificationControlQueue = new Queue<NotificationControl>(); /// <summary> /// 컨테이너 패널 /// </summary> private readonly Panel containerPanel; /// <summary> /// 현재 알림 컨트롤 /// </summary> private NotificationControl currentNotificationControl; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - NotificationHelper(containerPanel) /// <summary> /// 생성자 /// </summary> /// <param name="containerPanel">컨테이너 패널</param> public NotificationHelper(Panel containerPanel) { this.containerPanel = containerPanel; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 알림 표시하기 - ShowNotification(notificationControl) /// <summary> /// 알림 표시하기 /// </summary> /// <param name="notificationControl"></param> public void ShowNotification(NotificationControl notificationControl) { notificationControl.Closed += notificationControl_Closed; if(this.currentNotificationControl == null) { ShowNextNotification(notificationControl); } else { this.notificationControlQueue.Enqueue(notificationControl); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 알림 컨트롤 닫은 경우 처리하기 - notificationControl_Closed(sender, e) /// <summary> /// 알림 컨트롤 닫은 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void notificationControl_Closed(object sender, EventArgs e) { this.currentNotificationControl = null; if(this.notificationControlQueue.Count > 0) { ShowNextNotification(this.notificationControlQueue.Dequeue()); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 다음 알림 표시하기 - ShowNextNotification(notificationControl) /// <summary> /// 다음 알림 표시하기 /// </summary> /// <param name="notificationControl">알림 컨트롤</param> private void ShowNextNotification(NotificationControl notificationControl) { this.currentNotificationControl = notificationControl; this.containerPanel.Children.Add(notificationControl); } #endregion } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<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"> <Grid Name="grid"> <Button Name="showButton" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="10" Content="알림 메시지 표시" /> </Grid> </Window> |
■ Window 엘리먼트 로드시 UI 구성 요소를 오른쪽에서 왼쪽으로 슬라이드하는 애니메이션을 만드는 방법을 보여준다. ▶ 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 |
<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> <Storyboard x:Key="SlideInFromRightStoryboardKey"> <ThicknessAnimation Storyboard.TargetProperty="Margin" Duration="00:00:00.5" From="800 0 -800 0" To="0"> <ThicknessAnimation.EasingFunction> <CubicEase EasingMode="EaseOut" /> </ThicknessAnimation.EasingFunction> </ThicknessAnimation> </Storyboard> </Window.Resources> <Grid Margin="800 0 -800 0" Background="Transparent"> <Grid.Triggers> <EventTrigger RoutedEvent="Loaded"> <BeginStoryboard Storyboard="{StaticResource SlideInFromRightStoryboardKey}" /> </EventTrigger> </Grid.Triggers> <Ellipse Width="300" Height="300" Fill="Blue" /> <Ellipse Width="200" Height="200" Fill="Gold" /> </Grid> </Window> |
TestProject.zip
■ 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
■ Window 클래스에서 다중 모니터 중 하나의 모니터 화면 왼쪽에 윈도우를 위치시키는 방법을 보여준다. ▶ WindowPlacementHelper.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 |
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; namespace TestProject; /// <summary> /// 윈도우 배치 헬퍼 /// </summary> public class WindowPlacementHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region CWPRETSTRUCT - CWPRETSTRUCT /// <summary> /// CWPRETSTRUCT /// </summary> [StructLayout(LayoutKind.Sequential)] private struct CWPRETSTRUCT { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 결과 핸들 /// </summary> public IntPtr ResultHandle; /// <summary> /// LONG 매개 변수 /// </summary> public IntPtr LongParameter; /// <summary> /// WORD 매개 변수 /// </summary> public IntPtr WordParameter; /// <summary> /// 메시지 /// </summary> public uint Message; /// <summary> /// 윈도우 핸들 /// </summary> public IntPtr WindowHandle; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Delegate ////////////////////////////////////////////////////////////////////////////////////////// Private #region 후킹 프로시저 처리하기 - HookProcedure(code, wordParameter, longParameter) /// <summary> /// 후킹 프로시저 처리하기 /// </summary> /// <param name="code">코드</param> /// <param name="wordParameter">WORD 매개 변수</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> private delegate IntPtr HookProcedure(int code, IntPtr wordParameter, IntPtr longParameter); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 윈도우즈 후킹 설정하기 (확장) - SetWindowsHookEx(hookID, hookProcedure, instanceHandle, threadID) /// <summary> /// 윈도우즈 후킹 설정하기 (확장) /// </summary> /// <param name="hookID">후킹 ID</param> /// <param name="hookProcedure">후킹 프로시저</param> /// <param name="instanceHandle">인스턴스 핸들</param> /// <param name="threadID">쓰레드 ID</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern IntPtr SetWindowsHookEx(int hookID, HookProcedure hookProcedure, IntPtr instanceHandle, uint threadID); #endregion #region 윈도우즈 후킹 해제하기 (확장) - UnhookWindowsHookEx(instanceHandle) /// <summary> /// 윈도우즈 후킹 해제하기 (확장) /// </summary> /// <param name="instanceHandle">인스턴스 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool UnhookWindowsHookEx(IntPtr instanceHandle); #endregion #region 다음 후킹 호출하기 (확장) - CallNextHookEx(hookID, code, wordParameter, longParameter) /// <summary> /// 다음 후킹 호출하기 (확장) /// </summary> /// <param name="hookID">후킹 ID</param> /// <param name="code">코드</param> /// <param name="wordParameter">WORD 매개 변수</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern IntPtr CallNextHookEx(IntPtr hookID, int code, IntPtr wordParameter, IntPtr longParameter); #endregion #region 현재 쓰레드 ID 구하기 - GetCurrentThreadId() /// <summary> /// 현재 쓰레드 ID 구하기 /// </summary> /// <returns>현재 쓰레드 ID</returns> [DllImport("kernel32")] private static extern uint GetCurrentThreadId(); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// WH_CALLWNDPROCRET /// </summary> private const int WH_CALLWNDPROCRET = 12; /// <summary> /// WM_MOVE /// </summary> private const int WM_MOVE = 0x0003; /// <summary> /// WM_MOVING /// </summary> private const int WM_MOVING = 0x0216; /// <summary> /// WM_EXITSIZEMOVE /// </summary> private const int WM_EXITSIZEMOVE = 0x0232; /// <summary> /// 후킹 ID /// </summary> private IntPtr hookID = IntPtr.Zero; /// <summary> /// 후킹 프로시저 /// </summary> private HookProcedure hookProcedure; /// <summary> /// 이동 여부 /// </summary> private bool isMoving = false; /// <summary> /// 윈도우 /// </summary> private Window window; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - WindowPlacementHelper(window) /// <summary> /// 생성자 /// </summary> /// <param name="window">윈도우</param> public WindowPlacementHelper(Window window) { this.window = window; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 후킹하기 - Hook() /// <summary> /// 후킹하기 /// </summary> public void Hook() { this.hookProcedure = new HookProcedure(HookCallback); this.hookID = SetWindowsHookEx(WH_CALLWNDPROCRET, this.hookProcedure, IntPtr.Zero, GetCurrentThreadId()); } #endregion #region 후킹 해제하기 - Unhook() /// <summary> /// 후킹 해제하기 /// </summary> public void Unhook() { if(this.hookID != IntPtr.Zero) { UnhookWindowsHookEx(this.hookID); } } #endregion #region 윈도우 고정하기 - PinWindow(window) /// <summary> /// 윈도우 고정하기 /// </summary> /// <param name="window">윈도우</param> public void PinWindow(Window window) { nint windowHandle = new WindowInteropHelper(window).Handle; System.Windows.Forms.Screen currentScreen = System.Windows.Forms.Screen.FromHandle(windowHandle); System.Drawing.Rectangle workAreaRectangle = currentScreen.WorkingArea; window.Width = 400; window.Height = workAreaRectangle.Height + 7; window.Left = workAreaRectangle.Right - window.Width + 7; window.Top = workAreaRectangle.Top; PresentationSource presentationSource = PresentationSource.FromVisual(window); if(presentationSource != null) { double dpiX = presentationSource.CompositionTarget.TransformToDevice.M11; double dpiY = presentationSource.CompositionTarget.TransformToDevice.M22; window.Left /= dpiX; window.Top /= dpiY; } window.WindowState = WindowState.Normal; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 후킹 콜백 처리하기 - HookCallback(code, wordParameter, longParameter) /// <summary> /// 후킹 콜백 처리하기 /// </summary> /// <param name="code">코드</param> /// <param name="wordParameter">WORD 매개 변수</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> private IntPtr HookCallback(int code, IntPtr wordParameter, IntPtr longParameter) { if(code >= 0) { CWPRETSTRUCT cwpretstruct = (CWPRETSTRUCT)Marshal.PtrToStructure(longParameter, typeof(CWPRETSTRUCT)); IntPtr windowHandle = cwpretstruct.WindowHandle; uint message = cwpretstruct.Message; if(windowHandle == new WindowInteropHelper(this.window).Handle) { switch(message) { case WM_MOVING : this.isMoving = true; break; case WM_EXITSIZEMOVE : if(this.isMoving) { this.isMoving = false; this.window.Dispatcher.Invoke(() => { PinWindow(this.window); }); } break; } } } return CallNextHookEx(hookID, code, wordParameter, longParameter); } #endregion } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<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" WindowStyle="SingleBorderWindow" ResizeMode="CanMinimize" Title="TestProject" FontFamily="맑은고딕" FontSize="16"> </Window> |
▶ MainWindow.xaml.cs
■ Window 클래스에서 제목줄 마우스 드래그를 통해 윈도우 이동을 방지하는 방법을 보여준다. ▶ NonDraggableWindow.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 |
using System; using System.Windows; using System.Windows.Interop; namespace TestProject; /// <summary> /// 드래그 불가능 윈도우 /// </summary> public class NonDraggableWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// WM_NCLBUTTONDOWN /// </summary> private const int WM_NCLBUTTONDOWN = 0x00A1; /// <summary> /// HTCAPTION /// </summary> private const int HTCAPTION = 2; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 소스 초기화시 처리하기 - OnSourceInitialized(e) /// <summary> /// 소스 초기화시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); nint windowHandle = new WindowInteropHelper(this).Handle; HwndSource.FromHwnd(windowHandle)?.AddHook(WindowProcedure); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 윈도우 프로시저 처리하기 - WindowProcedure(windowHandle, message, wordParameter, longParameter, handled) /// <summary> /// 윈도우 프로시저 처리하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="message">메시지</param> /// <param name="wordParameter">WORD 매개 변수</param> /// <param name="longParameter">LONG 매개 변수</param> /// <param name="handled">처리 여부</param> /// <returns>처리 결과</returns> private IntPtr WindowProcedure(IntPtr windowHandle, int message, IntPtr wordParameter, IntPtr longParameter, ref bool handled) { if(message == WM_NCLBUTTONDOWN && wordParameter.ToInt32() == HTCAPTION) { handled = true; return IntPtr.Zero; } return IntPtr.Zero; } #endregion } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 |
<local:NonDraggableWindow 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" Title="TestProject" Width="800" Height="600" FontFamily="나눔고딕코딩" FontSize="16"> </local:NonDraggableWindow> |
▶ 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 |
namespace TestProject; /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : NonDraggableWindow { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); } #endregion } |
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