[C#/WPF] Adorner 클래스 : 슬라이딩 어도너 사용하기
■ Adorner 클래스를 사용해 슬라이딩 어도너를 만드는 방법을 보여준다. ▶ UIElementAdorner.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 |
using System; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Documents; using System.Windows.Media; namespace TestProject { /// <summary> /// UI 엘리먼트 어도너 /// </summary> public class UIElementAdorner : Adorner { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 자식 엘리먼트 /// </summary> private readonly UIElement childElement; /// <summary> /// 왼쪽 오프셋 /// </summary> private double leftOffset; /// <summary> /// 위쪽 오프셋 /// </summary> private double topOffset; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 왼쪽 오프셋 - LeftOffset /// <summary> /// 왼쪽 오프셋 /// </summary> public double LeftOffset { get { return this.leftOffset; } set { this.leftOffset = value; UpdateLocation(); } } #endregion #region 위쪽 오프셋 - TopOffset /// <summary> /// 위쪽 오프셋 /// </summary> public double TopOffset { get { return this.topOffset; } set { this.topOffset = value; UpdateLocation(); } } #endregion #region 논리적 자식 열거자 - LogicalChildren /// <summary> /// 논리적 자식 열거자 /// </summary> protected override IEnumerator LogicalChildren { get { List<UIElement> list = new List<UIElement> { this.childElement }; return list.GetEnumerator(); } } #endregion #region 비주얼 자식 수 - VisualChildrenCount /// <summary> /// 비주얼 자식 수 /// </summary> protected override int VisualChildrenCount { get { return 1; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - UIElementAdorner(adornedElement, childElement) /// <summary> /// 생성자 /// </summary> /// <param name="adornedElement">장식 엘리먼트</param> /// <param name="childElement">자식 엘리먼트</param> public UIElementAdorner(UIElement adornedElement, UIElement childElement) : base(adornedElement) { if(childElement == null) { throw new ArgumentNullException("childElement"); } this.childElement = childElement; AddLogicalChild(childElement); AddVisualChild(childElement); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 희망 변환 구하기 - GetDesiredTransform(transform) /// <summary> /// 희망 변환 구하기 /// </summary> /// <param name="transform">변환</param> /// <returns>희망 변환</returns> public override GeneralTransform GetDesiredTransform(GeneralTransform transform) { GeneralTransformGroup transformGroup = new GeneralTransformGroup(); transformGroup.Children.Add(base.GetDesiredTransform(transform)); transformGroup.Children.Add(new TranslateTransform(this.leftOffset, this.topOffset)); return transformGroup; } #endregion #region 오프셋 설정하기 - SetOffset(leftOffset, topOffset) /// <summary> /// 오프셋 설정하기 /// </summary> /// <param name="leftOffset">왼쪽 오프셋</param> /// <param name="topOffset">위쪽 오프셋</param> public void SetOffset(double leftOffset, double topOffset) { this.leftOffset = leftOffset; this.topOffset = topOffset; UpdateLocation(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 측정하기 (오버라이드) - MeasureOverride(availableSize) /// <summary> /// 측정하기 (오버라이드) /// </summary> /// <param name="availableSize">희망 크기</param> /// <returns>크기</returns> protected override Size MeasureOverride(Size availableSize) { this.childElement.Measure(availableSize); return this.childElement.DesiredSize; } #endregion #region 배열하기 (오버라이드) - ArrangeOverride(finalSize) /// <summary> /// 배열하기 (오버라이드) /// </summary> /// <param name="finalSize">최종 크기</param> /// <returns>크기</returns> protected override Size ArrangeOverride(Size finalSize) { this.childElement.Arrange(new Rect(finalSize)); return finalSize; } #endregion #region 비주얼 자식 구하기 - GetVisualChild(index) /// <summary> /// 비주얼 자식 구하기 /// </summary> /// <param name="index">인덱스</param> /// <returns>비주얼 자식</returns> protected override Visual GetVisualChild(int index) { return this.childElement; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 위치 업데이트하기 - UpdateLocation() /// <summary> /// 위치 업데이트하기 /// </summary> private void UpdateLocation() { AdornerLayer adornerLayer = Parent as AdornerLayer; if(adornerLayer != null) { adornerLayer.Update(AdornedElement); } } #endregion } } |
▶ SlidingElement.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 |
using System.Windows.Controls; namespace TestProject { /// <summary> /// 슬라이딩 엘리먼트 /// </summary> public class SlidingElement : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - SlidingElement(dataContext) /// <summary> /// 생성자 /// </summary> /// <param name="dataContext">데이터 컨텍스트</param> public SlidingElement(object dataContext) { DataContext = dataContext; } #endregion } } |
▶ SlidingAdorner.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 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; namespace TestProject { /// <summary> /// 슬라이딩 어도너 /// </summary> public class SlidingAdorner : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration ////////////////////////////////////////////////////////////////////////////////////////// Public #region SlidingAdornerSlideDirection /// <summary> /// 슬라이딩 어도너 슬라이드 방향 /// </summary> public enum SlidingAdornerSlideDirection { /// <summary> /// 오른쪽 /// </summary> Right, /// <summary> /// 왼쪽 /// </summary> Left, /// <summary> /// 위쪽 /// </summary> Up, /// <summary> /// 아래쪽 /// </summary> Down } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 슬라이드 방향 속성 - SlideDirectionProperty /// <summary> /// 슬라이드 방향 속성 /// </summary> public static readonly DependencyProperty SlideDirectionProperty = DependencyProperty.Register ( "SlideDirection", typeof(SlidingAdornerSlideDirection), typeof(SlidingAdorner), new UIPropertyMetadata(SlidingAdornerSlideDirection.Right) ); #endregion #region 슬라이드 거리 속성 - SlideDistanceProperty /// <summary> /// 슬라이드 거리 속성 /// </summary> public static readonly DependencyProperty SlideDistanceProperty = DependencyProperty.Register ( "SlideDistance", typeof(double), typeof(SlidingAdorner), new UIPropertyMetadata(100.0) ); #endregion #region 슬라이드 지속 시간 속성 - SlideDurationProperty /// <summary> /// 슬라이드 지속 시간 속성 /// </summary> public static readonly DependencyProperty SlideDurationProperty = DependencyProperty.Register ( "SlideDuration", typeof(int), typeof(SlidingAdorner), new UIPropertyMetadata(500) ); #endregion #region 슬라이드 엘리먼트 오프셋 속성 - SlideElementOffsetProperty /// <summary> /// 슬라이드 엘리먼트 오프셋 속성 /// </summary> public static readonly DependencyProperty SlideElementOffsetProperty = DependencyProperty.Register ( "SlideElementOffset", typeof(double), typeof(SlidingAdorner), new UIPropertyMetadata(0.0) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// UI 엘리먼트 어도너 /// </summary> private UIElementAdorner uiElementAdorner; /// <summary> /// 슬라이딩 엘리먼트 /// </summary> private SlidingElement slidingElement; /// <summary> /// 슬라이딩 엘리먼트 표시 여부 /// </summary> private bool isSlidingElementVisible; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 슬라이드 방향 - SlideDirection /// <summary> /// 슬라이드 방향 /// </summary> public SlidingAdornerSlideDirection SlideDirection { get { return (SlidingAdornerSlideDirection)GetValue(SlideDirectionProperty); } set { SetValue(SlideDirectionProperty, value); } } #endregion #region 슬라이드 거리 - SlideDistance /// <summary> /// 슬라이드 거리 /// </summary> public double SlideDistance { get { return (double)GetValue(SlideDistanceProperty); } set { SetValue(SlideDistanceProperty, value); } } #endregion #region 슬라이드 지속 시간 - SlideDuration /// <summary> /// 슬라이드 지속 시간 /// </summary> public int SlideDuration { get { return (int)GetValue(SlideDurationProperty); } set { SetValue(SlideDurationProperty, value); } } #endregion #region 슬라이드 엘리먼트 오프셋 - SlideElementOffset /// <summary> /// 슬라이드 엘리먼트 오프셋 /// </summary> public double SlideElementOffset { get { return (double)GetValue(SlideElementOffsetProperty); } set { SetValue(SlideElementOffsetProperty, value); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - SlidingAdorner() /// <summary> /// 생성자 /// </summary> public SlidingAdorner() { MouseEnter += Control_MouseEnter; MouseLeave += Control_MouseLeave; } #endregion #region 생성자 - SlidingAdorner(dataContext) /// <summary> /// 생성자 /// </summary> /// <param name="dataContext">데이터 컨텍스트</param> public SlidingAdorner(object dataContext) { DataContext = dataContext; MouseEnter += Control_MouseEnter; MouseLeave += Control_MouseLeave; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 변환 그룹 구하기 - GetTransformGroup(scaleX, scaleY, x, y) /// <summary> /// 변환 그룹 구하기 /// </summary> /// <param name="scaleX">스케일 X</param> /// <param name="scaleY">스케일 Y</param> /// <param name="x">X</param> /// <param name="y">Y</param> /// <returns>변환 그룹</returns> private static TransformGroup GetTransformGroup(double scaleX, double scaleY, int x, int y) { TransformGroup transformGroup = new TransformGroup(); ScaleTransform scaleTransform = new ScaleTransform { ScaleX = scaleX, ScaleY = scaleY }; transformGroup.Children.Add(scaleTransform); TranslateTransform translateTransform = new TranslateTransform { X = x, Y = y }; transformGroup.Children.Add(translateTransform); return transformGroup; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.slidingElement = new SlidingElement(DataContext); this.slidingElement.MouseLeave += slidingElement_MouseLeave; this.slidingElement.RenderTransform = GetTransformGroup(1, 1, 1, 1); switch(SlideDirection) { case SlidingAdornerSlideDirection.Right : case SlidingAdornerSlideDirection.Left : this.slidingElement.Width = SlideDistance; break; case SlidingAdornerSlideDirection.Down : case SlidingAdornerSlideDirection.Up : this.slidingElement.Height = SlideDistance; break; } this.uiElementAdorner = new UIElementAdorner(this, this.slidingElement); } #endregion //////////////////////////////////////////////////////////////////////////////// Private ////////////////////////////////////////////////////////////////////// Event #region 컨트롤 마우스 진입시 처리하기 - Control_MouseEnter(sender, e) /// <summary> /// 컨트롤 마우스 진입시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Control_MouseEnter(object sender, MouseEventArgs e) { if(!this.isSlidingElementVisible) { ShowSlidingAdorner(); } } #endregion #region 컨트롤 마우스 이탈시 처리하기 - Control_MouseLeave(sender, e) /// <summary> /// 컨트롤 마우스 이탈시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Control_MouseLeave(object sender, MouseEventArgs e) { ProcessMouseLeave(); } #endregion #region 슬라이딩 엘리먼트 마우스 이탈시 처리하기 - slidingElement_MouseLeave(sender, e) /// <summary> /// 슬라이딩 엘리먼트 마우스 이탈시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void slidingElement_MouseLeave(object sender, MouseEventArgs e) { ProcessMouseLeave(); } #endregion ////////////////////////////////////////////////////////////////////// Function #region 슬라이딩 어도너 표시하기 - ShowSlidingAdorner() /// <summary> /// 슬라이딩 어도너 표시하기 /// </summary> private void ShowSlidingAdorner() { AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this); if(adornerLayer == null) { return; } switch(SlideDirection) { case SlidingAdornerSlideDirection.Left : this.uiElementAdorner.SetOffset(-SlideElementOffset, 0); break; case SlidingAdornerSlideDirection.Right : this.uiElementAdorner.SetOffset(ActualWidth + SlideElementOffset, 0); break; case SlidingAdornerSlideDirection.Down : this.uiElementAdorner.SetOffset(0, ActualHeight + SlideElementOffset); break; case SlidingAdornerSlideDirection.Up : this.uiElementAdorner.SetOffset(0, -SlideElementOffset); break; } adornerLayer.Add(this.uiElementAdorner); AnimateScaleTransform(); AnimateTranslateTransform(); AnimateOpacity(); } #endregion #region 스케일 변환 애니메이션 적용하기 - AnimateScaleTransform() /// <summary> /// 스케일 변환 애니메이션 적용하기 /// </summary> private void AnimateScaleTransform() { SplineDoubleKeyFrame splineDoubleKeyFrame1 = new SplineDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)), Value = 0 }; SplineDoubleKeyFrame splineDoubleKeyFrame2 = new SplineDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(SlideDuration)), Value = 1 }; DoubleAnimationUsingKeyFrames doubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames(); doubleAnimationUsingKeyFrames.KeyFrames.Add(splineDoubleKeyFrame1); doubleAnimationUsingKeyFrames.KeyFrames.Add(splineDoubleKeyFrame2); ScaleTransform scaleTransform = ((TransformGroup)this.slidingElement.RenderTransform).Children[0] as ScaleTransform; if(scaleTransform != null) { switch(SlideDirection) { case SlidingAdornerSlideDirection.Right : case SlidingAdornerSlideDirection.Left : scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, doubleAnimationUsingKeyFrames); break; case SlidingAdornerSlideDirection.Down : case SlidingAdornerSlideDirection.Up : scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, doubleAnimationUsingKeyFrames); break; } } } #endregion #region 이동 변환 애니메이션 적용하기 - AnimateTranslateTransform() /// <summary> /// 이동 변환 애니메이션 적용하기 /// </summary> private void AnimateTranslateTransform() { SplineDoubleKeyFrame splineDoubleKeyFrame1 = new SplineDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0)), Value = 0 }; SplineDoubleKeyFrame splineDoubleKeyFrame2 = new SplineDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(SlideDuration)) }; switch(SlideDirection) { case SlidingAdornerSlideDirection.Right : case SlidingAdornerSlideDirection.Down : splineDoubleKeyFrame2.Value = 0; break; case SlidingAdornerSlideDirection.Left : case SlidingAdornerSlideDirection.Up : splineDoubleKeyFrame2.Value = -SlideDistance; break; } DoubleAnimationUsingKeyFrames doubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames(); doubleAnimationUsingKeyFrames.KeyFrames.Add(splineDoubleKeyFrame1); doubleAnimationUsingKeyFrames.KeyFrames.Add(splineDoubleKeyFrame2); TranslateTransform translateTransform = ((TransformGroup)this.slidingElement.RenderTransform).Children[1] as TranslateTransform; if(translateTransform != null) { switch(SlideDirection) { case SlidingAdornerSlideDirection.Right : case SlidingAdornerSlideDirection.Left : translateTransform.BeginAnimation(TranslateTransform.XProperty, doubleAnimationUsingKeyFrames); break; case SlidingAdornerSlideDirection.Down : case SlidingAdornerSlideDirection.Up : translateTransform.BeginAnimation(TranslateTransform.YProperty, doubleAnimationUsingKeyFrames); break; } } } #endregion #region 불투명도 애니메이션 적용하기 - AnimateOpacity() /// <summary> /// 불투명도 애니메이션 적용하기 /// </summary> private void AnimateOpacity() { DoubleAnimation doubleAnimation = new DoubleAnimation { Duration = new Duration(TimeSpan.FromMilliseconds(SlideDuration)), From = 0, To = 1 }; Storyboard storyboard = new Storyboard(); storyboard.Children.Add(doubleAnimation); Storyboard.SetTarget(doubleAnimation, this.slidingElement); Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(UIElement.Opacity)")); storyboard.Begin(); } #endregion #region 슬라이딩 어도너 숨기기 - HideSlidingAdorner() /// <summary> /// 슬라이딩 어도너 숨기기 /// </summary> private void HideSlidingAdorner() { AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this); if(adornerLayer != null) { adornerLayer.Remove(this.uiElementAdorner); } } #endregion #region 마우스 이탈시 처리하기 - ProcessMouseLeave() /// <summary> /// 마우스 이탈시 처리하기 /// </summary> private void ProcessMouseLeave() { if(!IsMouseOver && !this.slidingElement.IsMouseOver) { HideSlidingAdorner(); this.isSlidingElementVisible = false; } else { this.isSlidingElementVisible = true; } } #endregion } } |
▶ DragCanvas.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 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Media3D; namespace TestProject { /// <summary> /// 드래그 캔버스 /// </summary> public class DragCanvas : Canvas { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 드래그 가능 여부 첨부 속성 - CanBeDraggedProperty /// <summary> /// 드래그 가능 여부 첨부 속성 /// </summary> public static readonly DependencyProperty CanBeDraggedProperty = DependencyProperty.RegisterAttached ( "CanBeDragged", typeof(bool), typeof(DragCanvas), new UIPropertyMetadata(true) ); #endregion #region 드래그 허용 여부 속성 - AllowDraggingProperty /// <summary> /// 드래그 허용 여부 속성 /// </summary> public static readonly DependencyProperty AllowDraggingProperty = DependencyProperty.Register ( "AllowDragging", typeof(bool), typeof(DragCanvas), new PropertyMetadata(true) ); #endregion #region 뷰 외부 드래그 허용 여부 속성 - AllowDragOutOfViewProperty /// <summary> /// 뷰 외부 드래그 허용 여부 속성 /// </summary> public static readonly DependencyProperty AllowDragOutOfViewProperty = DependencyProperty.Register ( "AllowDragOutOfView", typeof(bool), typeof(DragCanvas), new UIPropertyMetadata(false) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 드래그 엘리먼트 /// </summary> private UIElement dragElement; /// <summary> /// 드래그 시작 포인트 /// </summary> private Point dragStartPoint; /// <summary> /// 드래그 시작 오프셋 X /// </summary> private double dragStartOffsetX; /// <summary> /// 드래그 시작 오프셋 Y /// </summary> private double dragStartOffsetY; /// <summary> /// 수정 오프셋 X /// </summary> private bool modifyOffsetX; /// <summary> /// 수정 오프셋 Y /// </summary> private bool modifyOffsetY; /// <summary> /// 드래그 여부 /// </summary> private bool isDragging; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 드래그 허용 여부 - AllowDragging /// <summary> /// 드래그 허용 여부 /// </summary> public bool AllowDragging { get { return (bool)GetValue(AllowDraggingProperty); } set { SetValue(AllowDraggingProperty, value); } } #endregion #region 뷰 외부 드래그 허용 여부 - AllowDragOutOfView /// <summary> /// 뷰 외부 드래그 허용 여부 /// </summary> public bool AllowDragOutOfView { get { return (bool)GetValue(AllowDragOutOfViewProperty); } set { SetValue(AllowDragOutOfViewProperty, value); } } #endregion #region 드래그 엘리먼트 - ElementBeingDragged /// <summary> /// 드래그 엘리먼트 /// </summary> public UIElement ElementBeingDragged { get { return !AllowDragging ? null : this.dragElement; } protected set { if(this.dragElement != null) { this.dragElement.ReleaseMouseCapture(); } if(!AllowDragging) { this.dragElement = null; } else { if(GetCanBeDragged(value)) { this.dragElement = value; this.dragElement.CaptureMouse(); } else { this.dragElement = null; } } } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 드래그 가능 여부 구하기 - GetCanBeDragged(element) /// <summary> /// 드래그 가능 여부 구하기 /// </summary> /// <param name="element">엘리먼트</param> /// <returns>드래그 가능 여부</returns> public static bool GetCanBeDragged(UIElement element) { if(element == null) { return false; } return (bool)element.GetValue(CanBeDraggedProperty); } #endregion #region 드래그 가능 여부 설정하기 - SetCanBeDragged(element, value) /// <summary> /// 드래그 가능 여부 설정하기 /// </summary> /// <param name="element">엘리먼트</param> /// <param name="value">값</param> public static void SetCanBeDragged(UIElement element, bool value) { if(element != null) { element.SetValue(CanBeDraggedProperty, value); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 전면으로 배치하기 - BringToFront(element) /// <summary> /// 전면으로 배치하기 /// </summary> /// <param name="element">엘리먼트</param> public void BringToFront(UIElement element) { UpdateZOrder(element, true); } #endregion #region 후면으로 배치하기 - SendToBack(element) /// <summary> /// 후면으로 배치하기 /// </summary> /// <param name="element">엘리먼트</param> public void SendToBack(UIElement element) { UpdateZOrder(element, false); } #endregion #region 캔버스 자식 찾기 - FindCanvasChild(dependencyObject) /// <summary> /// 캔버스 자식 찾기 /// </summary> /// <param name="dependencyObject">의존 객체</param> /// <returns>캔버스 자식</returns> public UIElement FindCanvasChild(DependencyObject dependencyObject) { while(dependencyObject != null) { UIElement element = dependencyObject as UIElement; if(element != null && Children.Contains(element)) { break; } if(dependencyObject is Visual || dependencyObject is Visual3D) { dependencyObject = VisualTreeHelper.GetParent(dependencyObject); } else { dependencyObject = LogicalTreeHelper.GetParent(dependencyObject); } } return dependencyObject as UIElement; } #endregion //////////////////////////////////////////////////////////////////////////////// Protected #region PREVIEW 마우스 왼쪽 버튼 DOWN 처리하기 - OnPreviewMouseLeftButtonDown(e) /// <summary> /// PREVIEW 마우스 왼쪽 버튼 DOWN 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnPreviewMouseLeftButtonDown(e); this.isDragging = false; this.dragStartPoint = e.GetPosition(this); ElementBeingDragged = FindCanvasChild(e.Source as DependencyObject); if(ElementBeingDragged == null) { return; } double left = GetLeft (ElementBeingDragged); double right = GetRight (ElementBeingDragged); double top = GetTop (ElementBeingDragged); double bottom = GetBottom(ElementBeingDragged); this.dragStartOffsetX = ResolveOffset(left, right , out this.modifyOffsetX); this.dragStartOffsetY = ResolveOffset(top , bottom, out this.modifyOffsetY); e.Handled = true; this.isDragging = true; } #endregion #region PREVIEW 마우스 이동시 처리하기 - OnPreviewMouseMove(e) /// <summary> /// PREVIEW 마우스 이동시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPreviewMouseMove(MouseEventArgs e) { base.OnPreviewMouseMove(e); if(ElementBeingDragged == null || !this.isDragging) { return; } Point cursorPoint = e.GetPosition(this); double newOffsetX; double newOffsetY; if(this.modifyOffsetX) { newOffsetX = this.dragStartOffsetX + (cursorPoint.X - this.dragStartPoint.X); } else { newOffsetX = this.dragStartOffsetX - (cursorPoint.X - this.dragStartPoint.X); } if(this.modifyOffsetY) { newOffsetY = this.dragStartOffsetY + (cursorPoint.Y - this.dragStartPoint.Y); } else { newOffsetY = this.dragStartOffsetY - (cursorPoint.Y - this.dragStartPoint.Y); } if(!AllowDragOutOfView) { Rect elementRectangle = CalculateDragElementRectangle(newOffsetX, newOffsetY); bool alignLeft = elementRectangle.Left < 0; bool alignRight = elementRectangle.Right > ActualWidth; if(alignLeft) { newOffsetX = this.modifyOffsetX ? 0 : ActualWidth - elementRectangle.Width; } else if(alignRight) { newOffsetX = this.modifyOffsetX ? ActualWidth - elementRectangle.Width : 0; } bool alignTop = elementRectangle.Top < 0; bool alignBottom = elementRectangle.Bottom > ActualHeight; if(alignTop) { newOffsetY = this.modifyOffsetY ? 0 : ActualHeight - elementRectangle.Height; } else if(alignBottom) { newOffsetY = this.modifyOffsetY ? ActualHeight - elementRectangle.Height : 0; } } if(this.modifyOffsetX) { SetLeft(ElementBeingDragged, newOffsetX); } else { SetRight(ElementBeingDragged, newOffsetX); } if(this.modifyOffsetY) { SetTop(ElementBeingDragged, newOffsetY); } else { SetBottom(ElementBeingDragged, newOffsetY); } } #endregion #region PREVIEW 마우스 UP 처리하기 - OnPreviewMouseUp(e) /// <summary> /// PREVIEW 마우스 UP 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPreviewMouseUp(MouseButtonEventArgs e) { base.OnPreviewMouseUp(e); ElementBeingDragged = null; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 드래그 엘리먼트 사각형 계산하기 - CalculateDragElementRectangle(newOffsetX, newOffsetY) /// <summary> /// 드래그 엘리먼트 사각형 계산하기 /// </summary> /// <param name="newOffsetX">신규 오프셋 X</param> /// <param name="newOffsetY">신규 오프셋 Y</param> /// <returns>드래그 엘리먼트 사각형</returns> private Rect CalculateDragElementRectangle(double newOffsetX, double newOffsetY) { if(ElementBeingDragged == null) { throw new InvalidOperationException("ElementBeingDragged is null."); } Size elementSize = ElementBeingDragged.RenderSize; double x; double y; if(this.modifyOffsetX) { x = newOffsetX; } else { x = ActualWidth - newOffsetX - elementSize.Width; } if(this.modifyOffsetY) { y = newOffsetY; } else { y = ActualHeight - newOffsetY - elementSize.Height; } Point elementPoint = new Point(x, y); return new Rect(elementPoint, elementSize); } #endregion #region 오프셋 결정하기 - ResolveOffset(side1, side2, useSide1) /// <summary> /// 오프셋 결정하기 /// </summary> /// <param name="side1">측면 1</param> /// <param name="side2">측면 2</param> /// <param name="useSide1">측면 1 사용 여부</param> /// <returns>오프셋</returns> private static double ResolveOffset(double side1, double side2, out bool useSide1) { useSide1 = true; double result; if(double.IsNaN(side1)) { if(double.IsNaN(side2)) { result = 0; } else { result = side2; useSide1 = false; } } else { result = side1; } return result; } #endregion #region Z 순서 업데이트하기 - UpdateZOrder(element, bringToFront) /// <summary> /// Z 순서 업데이트하기 /// </summary> /// <param name="element">엘리먼트</param> /// <param name="bringToFront">전면 배치 여부</param> private void UpdateZOrder(UIElement element, bool bringToFront) { if(element == null) { return; } if(!Children.Contains(element)) { throw new ArgumentException("Must be a child element of the Canvas.", "element"); } int elementNewZIndex = -1; if(bringToFront) { foreach(UIElement childElement in Children) { if(childElement.Visibility != Visibility.Collapsed) { ++elementNewZIndex; } } } else { elementNewZIndex = 0; } int offset = (elementNewZIndex == 0) ? +1 : -1; int elementCurrentZIndex = GetZIndex(element); foreach(UIElement childElement in Children) { if(childElement == element) { SetZIndex(element, elementNewZIndex); } else { int zIndex = GetZIndex(childElement); if(bringToFront && elementCurrentZIndex < zIndex || !bringToFront && zIndex < elementCurrentZIndex) { SetZIndex(childElement, zIndex + offset); } } } } #endregion } } |
▶