■ DatePicker 컨트롤을 만드는 방법을 보여준다.
▶ DatePicker.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 |
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:g="clr-namespace:System.Globalization;assembly=mscorlib" x:Class="TestProject.DatePicker"> <UserControl.Resources> <Style TargetType="{x:Type RepeatButton}"> <Setter Property="Width" Value="{Binding RelativeSource={RelativeSource self}, Path=ActualHeight}" /> <Setter Property="Focusable" Value="False" /> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=nullCheckBox, Path=IsChecked}" Value="True"> <Setter Property="IsEnabled" Value="False" /> </DataTrigger> </Style.Triggers> </Style> <Style TargetType="{x:Type StatusBarItem}"> <Setter Property="Margin" Value="1" /> <Setter Property="HorizontalAlignment" Value="Center" /> <Setter Property="VerticalAlignment" Value="Center" /> </Style> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="Transparent" /> <Setter Property="Margin" Value="1" /> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Style.Triggers> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="True" /> <Condition Property="Selector.IsSelectionActive" Value="False" /> </MultiTrigger.Conditions> <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" /> </MultiTrigger> <DataTrigger Binding="{Binding ElementName=nullCheckBox, Path=IsChecked}" Value="True"> <Setter Property="IsEnabled" Value="False" /> </DataTrigger> </Style.Triggers> </Style> </UserControl.Resources> <Border BorderThickness="1" BorderBrush="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid Background="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}" TextBlock.Foreground="{DynamicResource {x:Static SystemColors.ControlLightLightBrushKey}}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <RepeatButton Grid.Column="0" FontWeight="Bold" Content="<" Click="previousRepeatButton_Click" /> <TextBlock Name="monthYearTextBlock" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="3" /> <RepeatButton Grid.Column="2" FontWeight="Bold" Content=">" Click="nextRepeatButton_Click" /> </Grid> <StatusBar Grid.Row="1" ItemsSource="{Binding Source={x:Static g:DateTimeFormatInfo.CurrentInfo}, Path=AbbreviatedDayNames}"> <StatusBar.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Rows="1" /> </ItemsPanelTemplate> </StatusBar.ItemsPanel> </StatusBar> <Border Grid.Row="2" BorderThickness="0 1 0 1" BorderBrush="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"> <ListBox Name="monthListBox" SelectionChanged="monthListBox_SelectionChanged"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Name="monthUniformGrid" Background="{DynamicResource {x:Static SystemColors.ControlLightBrushKey}}" Columns="7" Rows="6" IsItemsHost="True" /> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBoxItem>더미 항목</ListBoxItem> </ListBox> </Border> <CheckBox Name="nullCheckBox" Grid.Row="3" Margin="3" HorizontalAlignment="Center" VerticalAlignment="Center" Checked="nullCheckBox_Checked" Unchecked="nullCheckBox_Unchecked"> 미적용 </CheckBox> </Grid> </Border> </UserControl> |
▶ DatePicker.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 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 |
using System; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; namespace TestProject { /// <summary> /// 일자 선택기 /// </summary> public partial class DatePicker { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 일자 변경시 - DateChanged /// <summary> /// 일자 변경시 /// </summary> public event RoutedPropertyChangedEventHandler<DateTime?> DateChanged { add { AddHandler(DateChangedEvent, value); } remove { RemoveHandler(DateChangedEvent, value); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 일자 속성 /// </summary> public static readonly DependencyProperty DateProperty = DependencyProperty.Register ( "Date", typeof(DateTime?), typeof(DatePicker), new PropertyMetadata ( new DateTime(), DatePropertyChangedCallback ) ); /// <summary> /// 일자 변경 이벤트 /// </summary> public static readonly RoutedEvent DateChangedEvent = EventManager.RegisterRoutedEvent ( "DateChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<DateTime?>), typeof(DatePicker) ); #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 월 유니폼 그리드 /// </summary> private UniformGrid monthUniformGrid; /// <summary> /// 저장 일시 /// </summary> private DateTime dateTimeSaved = DateTime.Now.Date; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 일자 - Date /// <summary> /// 일자 /// </summary> public DateTime? Date { set { SetValue(DateProperty, value); } get { return (DateTime?)GetValue(DateProperty); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DatePicker() /// <summary> /// 생성자 /// </summary> public DatePicker() { InitializeComponent(); Date = dateTimeSaved; Loaded += userControl_Loaded; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private ////////////////////////////////////////////////////////////////////// Event #region 일자 속성 변경 콜백 처리하기 - DatePropertyChangedCallback(dependencyObject, e) /// <summary> /// 일자 속성 변경 콜백 처리하기 /// </summary> /// <param name="dependencyObject">의존 객체</param> /// <param name="e">이벤트 인자</param> private static void DatePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { (dependencyObject as DatePicker).OnDateChanged((DateTime?)e.OldValue, (DateTime?)e.NewValue); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Protected #region 미리보기 키 DOWN 처리하기 - OnPreviewKeyDown(e) /// <summary> /// 미리보기 키 DOWN 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPreviewKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if(e.Key == Key.PageDown) { FlipPage(true); e.Handled = true; } else if(e.Key == Key.PageUp) { FlipPage(false); e.Handled = false; } } #endregion #region 일자 변경시 처리하기 - OnDateChanged(beforeDateTime, afterDateTime) /// <summary> /// 일자 변경시 처리하기 /// </summary> /// <param name="beforeDateTime">변경전 일시</param> /// <param name="afterDateTime">변경후 일시</param> protected virtual void OnDateChanged(DateTime? beforeDateTime, DateTime? afterDateTime) { this.nullCheckBox.IsChecked = (afterDateTime == null); if(afterDateTime != null) { DateTime newDateTime = (DateTime)afterDateTime; this.monthYearTextBlock.Text = newDateTime.ToString(DateTimeFormatInfo.CurrentInfo.YearMonthPattern); if(this.monthUniformGrid != null) { this.monthUniformGrid.FirstColumn = (int)(new DateTime(newDateTime.Year, newDateTime.Month, 1).DayOfWeek); } int dayCountInMonth = DateTime.DaysInMonth(newDateTime.Year, newDateTime.Month); if(dayCountInMonth != this.monthListBox.Items.Count) { this.monthListBox.BeginInit(); this.monthListBox.Items.Clear(); for(int i = 0; i < dayCountInMonth; i++) { this.monthListBox.Items.Add((i + 1).ToString()); } this.monthListBox.EndInit(); } this.monthListBox.SelectedIndex = newDateTime.Day - 1; } RoutedPropertyChangedEventArgs<DateTime?> e = new RoutedPropertyChangedEventArgs<DateTime?> ( beforeDateTime, afterDateTime, DatePicker.DateChangedEvent ); e.Source = this; RaiseEvent(e); } #endregion //////////////////////////////////////////////////////////////////////////////// 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) { this.monthUniformGrid = FindElement<UniformGrid>(this.monthListBox); if(Date != null) { DateTime dateTime = (DateTime)Date; this.monthUniformGrid.FirstColumn = (int)(new DateTime(dateTime.Year, dateTime.Month, 1).DayOfWeek); } } #endregion #region 이전 리피트 버튼 클릭시 처리하기 - previousRepeatButton_Click(sender, e) /// <summary> /// 이전 리피트 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void previousRepeatButton_Click(object sender, RoutedEventArgs e) { FlipPage(true); } #endregion #region 다음 리피트 버튼 클릭시 처리하기 - nextRepeatButton_Click(sender, e) /// <summary> /// 다음 리피트 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void nextRepeatButton_Click(object sender, RoutedEventArgs e) { FlipPage(false); } #endregion #region 월 리스트 박스 선택 변경시 처리하기 - monthListBox_SelectionChanged(sender, e) /// <summary> /// 월 리스트 박스 선택 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void monthListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(Date == null) { return; } DateTime dateTime = (DateTime)Date; if(this.monthListBox.SelectedIndex != -1) { Date = new DateTime(dateTime.Year, dateTime.Month, int.Parse(this.monthListBox.SelectedItem as string)); } } #endregion #region NULL 체크 박스 체크시 처리하기 - nullCheckBox_Checked(sender, e) /// <summary> /// NULL 체크 박스 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void nullCheckBox_Checked(object sender, RoutedEventArgs e) { if(Date != null) { dateTimeSaved = (DateTime)Date; Date = null; } } #endregion #region NULL 체크 박스 체크 해제시 처리하기 - nullCheckBox_Unchecked(sender, e) /// <summary> /// NULL 체크 박스 체크 해제시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void nullCheckBox_Unchecked(object sender, RoutedEventArgs e) { Date = dateTimeSaved; } #endregion ////////////////////////////////////////////////////////////////////// Function #region 엘리먼트 찾기 - FindElement<T>(sourceDependencyObject) /// <summary> /// 엘리먼트 찾기 /// </summary> /// <typeparam name="TElement">엘리먼트 타입</typeparam> /// <param name="sourceDependencyObject">소스 의존 객체</param> /// <returns>엘리먼트</returns> private TElement FindElement<TElement>(DependencyObject sourceDependencyObject) where TElement : class { if(sourceDependencyObject is TElement) { return sourceDependencyObject as TElement; } for(int i = 0; i < VisualTreeHelper.GetChildrenCount(sourceDependencyObject); i++) { Visual visual = FindElement<TElement>(VisualTreeHelper.GetChild(sourceDependencyObject, i)) as Visual; if(visual != null) { return visual as TElement; } } return null; } #endregion #region 페이지 넘기기 - FlipPage(isPrevious) /// <summary> /// 페이지 넘기기 /// </summary> /// <param name="isPrevious">이전 여부</param> private void FlipPage(bool isPrevious) { if(Date == null) { return; } DateTime dateTime = (DateTime)Date; int pageCount = isPrevious ? -1 : 1; if(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { pageCount *= 12; } if(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { pageCount = Math.Max(-1200, Math.Min(1200, 120 * pageCount)); } int year = dateTime.Year + pageCount / 12; int month = dateTime.Month + pageCount % 12; while(month < 1) { month += 12; year -= 1; } while(month > 12) { month -= 12; year += 1; } if(year < DateTime.MinValue.Year) { Date = DateTime.MinValue.Date; } else if(year > DateTime.MaxValue.Year) { Date = DateTime.MaxValue.Date; } else { Date = new DateTime(year, month, Math.Min(dateTime.Day, DateTime.DaysInMonth(year, month))); } } #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 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:TestProject" SizeToContent="WidthAndHeight" ResizeMode="CanMinimize" Title="일자 선택기 테스트"> <StackPanel> <src:DatePicker x:Name="datePicker" Margin="12" HorizontalAlignment="Center" DateChanged="datePicker_DateChanged" /> <StackPanel Margin="12" Orientation="Horizontal"> <TextBlock Text="바인딩 값 : " /> <TextBlock Text="{Binding ElementName=datePicker, Path=Date}" /> </StackPanel> <StackPanel Margin="12" Orientation="Horizontal"> <TextBlock Text="이벤트 핸들러 값 : " /> <TextBlock Name="dateTextBlock" /> </StackPanel> </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 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// private #region 일자 선택기 일자 변경시 처리하기 - datePicker_DateChanged(sender, e) /// <summary> /// 일자 선택기 일자 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void datePicker_DateChanged(object sender, RoutedPropertyChangedEventArgs<DateTime?> e) { if(e.NewValue != null) { DateTime dateTime = (DateTime)e.NewValue; this.dateTextBlock.Text = dateTime.ToString("d"); } else { this.dateTextBlock.Text = string.Empty; } } #endregion } } |