■ Behavior<T> 클래스를 사용해 윈도우 종료시 동작을 만들기
▶ WindowClosingBehavior.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.ComponentModel; using System.Windows; using System.Windows.Interactivity; using System.Windows.Media.Animation; namespace TestProject { /// <summary> /// 윈도우 종료시 동작 /// </summary> public class WindowClosingBehavior : Behavior<Window> { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 부착시 처리하기 - OnAttached() /// <summary> /// 부착시 처리하기 /// </summary> protected override void OnAttached() { AssociatedObject.Closing += AssociatedObject_Closing; } #endregion #region 탈착시 처리하기 - OnDetaching() /// <summary> /// 탈착시 처리하기 /// </summary> protected override void OnDetaching() { AssociatedObject.Closing -= AssociatedObject_Closing; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 결합 객체 종료 전 처리하기 - AssociatedObject_Closing(sender, e) /// <summary> /// 결합 객체 종료 전 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void AssociatedObject_Closing(object sender, CancelEventArgs e) { Window window = sender as Window; window.Closing -= AssociatedObject_Closing; e.Cancel = true; DoubleAnimation animation = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(0.5)); animation.Completed += (s, _) => window.Close(); window.BeginAnimation(UIElement.OpacityProperty, animation); } #endregion } } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<Window x:Class="TestProject.MainWindow" Name="window" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="Behavior<T> 클래스 : 윈도우 종료시 동작 사용하기" FontFamily="나눔고딕코딩" FontSize="16"> <i:Interaction.Behaviors> <local:WindowClosingBehavior /> </i:Interaction.Behaviors> </Window> |