■ ICommand 인터페이스에서 대리자 명령을 사용하는 방법을 보여준다.
▶ DelegateCommand.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 |
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Threading; namespace TestProject { /// <summary> /// 대리자 명령 /// </summary> public class DelegateCommand : ICommand { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 실행 가능 여부 변경시 이벤트 - CanExecuteChanged /// <summary> /// 실행 가능 여부 변경시 이벤트 /// </summary> public event EventHandler CanExecuteChanged { add => CommandManager.RequerySuggested += value; remove => CommandManager.RequerySuggested -= value; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 잠금 객체 /// </summary> private readonly object lockObject = new object(); /// <summary> /// 실행 액션 /// </summary> private readonly Action<object> executeAction; /// <summary> /// 실행 가능 여부 함수 /// </summary> private readonly Func<object, bool> canExecuteFunc; /// <summary> /// 실행 여부 /// </summary> private bool isExecuting; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 실행 여부 - IsExecuting /// <summary> /// 실행 여부 /// </summary> public bool IsExecuting { get { lock(this.lockObject) { return this.isExecuting; } } private set { lock(this.lockObject) { this.isExecuting = value; } } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DelegateCommand(executeAction, canExecuteFunc) /// <summary> /// 생성자 /// </summary> /// <param name="executeAction">실행 액션</param> /// <param name="canExecuteFunc">실행 가능 여부 함수</param> public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecuteFunc) { if(executeAction == null) { throw new ArgumentNullException(nameof(executeAction)); } this.canExecuteFunc = canExecuteFunc; this.executeAction = parameter => { bool canExecute = this.canExecuteFunc?.Invoke(parameter) ?? true; if(canExecute) { executeAction(parameter); } }; } #endregion #region 생성자 - DelegateCommand(executeAction) /// <summary> /// 생성자 /// </summary> /// <param name="executeAction">실행 액션</param> public DelegateCommand(Action<object> executeAction) : this(executeAction, null) { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 실행 가능 여부 구하기 - CanExecute(parameter) /// <summary> /// 실행 가능 여부 구하기 /// </summary> /// <param name="parameter">매개 변수</param> /// <returns>실행 가능 여부</returns> [DebuggerStepThrough] public bool CanExecute(object parameter) { if(IsExecuting) { return false; } return this.canExecuteFunc == null || this.canExecuteFunc(parameter); } #endregion #region 실행 가능 여부 구하기 - CanExecute() /// <summary> /// 실행 가능 여부 구하기 /// </summary> /// <returns>실행 가능 여부</returns> public bool CanExecute() => CanExecute(null); #endregion #region 비동기 실행하기 - ExecuteAsync(parameter) /// <summary> /// 비동기 실행하기 /// </summary> /// <param name="parameter">매개 변수</param> /// <returns>구성 태스크 대기 가능형</returns> public ConfiguredTaskAwaitable ExecuteAsync(object parameter) { return Task.Run ( (Func<Task>) ( async () => { if(IsExecuting) { return; } try { IsExecuting = true; await Application.Current.Dispatcher.BeginInvoke ( this.executeAction, DispatcherPriority.Normal, parameter ); } catch(Exception exception) { Debug.WriteLine($"Could not execute command. {exception.Message}"); throw; } finally { IsExecuting = false; CommandManager.InvalidateRequerySuggested(); } } ) ).ConfigureAwait(true); } #endregion #region 비동기 실행하기 - ExecuteAsync() /// <summary> /// 비동기 실행하기 /// </summary> /// <returns>구성 태스크 대기 가능형</returns> public ConfiguredTaskAwaitable ExecuteAsync() => ExecuteAsync(null); #endregion #region 실행하기 - Execute(parameter) /// <summary> /// 실행하기 /// </summary> /// <param name="parameter">매개 변수</param> public void Execute(object parameter) => ExecuteAsync(parameter); #endregion #region 실행하기 - Execute() /// <summary> /// 실행하기 /// </summary> public void Execute() => ExecuteAsync(null); #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 |
<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="ICommand 인터페이스 : 대리자 명령 사용하기" FontFamily="나눔고딕코딩" FontSize="16"> <Grid> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <Button HorizontalAlignment="Center" Margin="10" Width="100" Height="30" Command="{Binding RunCommand}" Content="테스트" /> <ListBox Name="listBox" HorizontalAlignment="Center" Margin="10" Width="300" Height="300" /> </StackPanel> </Grid> </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 |
using System; using System.Windows; using System.Threading.Tasks; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 실행 명령 /// </summary> private DelegateCommand runCommand; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 실행 명령 - RunCommand /// <summary> /// 실행 명령 /// </summary> public DelegateCommand RunCommand => this.runCommand ?? ( this.runCommand = new DelegateCommand ( async parameter => { this.listBox.Items.Add($"[{DateTime.Now.ToString("HH:mm:ss")}] 버튼을 클릭했습니다."); await Task.Delay(3000); this.listBox.Items.Add($"[{DateTime.Now.ToString("HH:mm:ss")}] 작업을 실행했습니다."); } ) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); DataContext = this; } #endregion } } |