■ BindingGroup 엘리먼트를 사용해 바인딩을 검증하는 방법을 보여준다.
▶ EntryDataValidationRule.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 |
using System; using System.Windows.Controls; using System.Windows.Data; using System.Globalization; namespace TestProject { /// <summary> /// 입력 데이터 검증 규칙 /// </summary> public class EntryDataValidationRule : ValidationRule { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 검증하기 - Validate(value, cultureInfo) /// <summary> /// 검증하기 /// </summary> /// <param name="value">값</param> /// <param name="cultureInfo">문화 정보</param> /// <returns>검증 결과</returns> public override ValidationResult Validate(object value, CultureInfo cultureInfo) { BindingGroup bindingGroup = value as BindingGroup; PurchaseItem item = bindingGroup.Items[0] as PurchaseItem; object priceObject; object offerExpireDateObject; bool priceResult = bindingGroup.TryGetValue(item, "Price" , out priceObject ); bool dateResult = bindingGroup.TryGetValue(item, "OfferExpireDate", out offerExpireDateObject); if(!priceResult || !dateResult) { return new ValidationResult(false, "속성을 찾을 수가 없습니다."); } double price = (double)priceObject; DateTime offerExpireDate = (DateTime)offerExpireDateObject; if(price > 100) { if(offerExpireDate < DateTime.Today + new TimeSpan(7, 0, 0, 0)) { return new ValidationResult(false, "100불 이상의 항목은 최소 7일 이내에서 이용 가능합니다."); } } return ValidationResult.ValidResult; } #endregion } } |
▶ PriceValidationRule.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 |
using System; using System.Windows.Controls; using System.Globalization; namespace TestProject { /// <summary> /// 가격 검증 규칙 /// </summary> public class PriceValidationRule : ValidationRule { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 검증하기 - Validate(value, cultureInfo) /// <summary> /// 검증하기 /// </summary> /// <param name="value">값</param> /// <param name="cultureInfo">문화 정보</param> /// <returns>검증 결과</returns> public override ValidationResult Validate(object value, CultureInfo cultureInfo) { try { double price = Convert.ToDouble(value); if(price < 0) { return new ValidationResult(false, "가격은 양수이어야 합니다."); } else { return ValidationResult.ValidResult; } } catch(Exception) { return new ValidationResult(false, "가격은 숫자이어야 합니다."); } } #endregion } } |
▶ DateValidationRule.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 |
using System; using System.Windows.Controls; using System.Globalization; namespace TestProject { /// <summary> /// 날짜 검증 규칙 /// </summary> public class DateValidationRule : ValidationRule { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 검증하기 - Validate(value, cultureInfo) /// <summary> /// 검증하기 /// </summary> /// <param name="value">값</param> /// <param name="cultureInfo">문화 정보</param> /// <returns>검증 결과</returns> public override ValidationResult Validate(object value, CultureInfo cultureInfo) { DateTime date; try { date = DateTime.Parse(value.ToString()); } catch(FormatException) { return new ValidationResult(false, "값이 적절한 날짜가 아닙니다."); } if(DateTime.Now.Date > date) { return new ValidationResult(false, "날짜는 오늘 이후 날짜이어야 합니다."); } else { return ValidationResult.ValidResult; } } #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 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 |
<Window x:Class="TestProject.MainWnidow" 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="BindingGroup 엘리먼트 : 바인딩 검증하기" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel Name="stackPanel" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10"> <StackPanel.Resources> <Style TargetType="HeaderedContentControl"> <Setter Property="Margin" Value="10" /> <Setter Property="Focusable" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="HeaderedContentControl"> <DockPanel LastChildFill="False"> <ContentPresenter DockPanel.Dock="Left" VerticalAlignment="Center" Focusable="False" ContentSource="Header" /> <ContentPresenter DockPanel.Dock="Right" VerticalAlignment="Center" Margin="5 0 0 0" ContentSource="Content" /> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </StackPanel.Resources> <StackPanel.BindingGroup> <BindingGroup NotifyOnValidationError="True"> <BindingGroup.ValidationRules> <local:EntryDataValidationRule ValidationStep="ConvertedProposedValue" /> </BindingGroup.ValidationRules> </BindingGroup> </StackPanel.BindingGroup> <TextBlock Margin="10" Text="판매용 항목을 입력해 주시기 바랍니다." /> <HeaderedContentControl Header="설명"> <TextBox Margin="10" Width="150" Height="25" VerticalContentAlignment="Center" Text="{Binding Path=Description, Mode=TwoWay}" /> </HeaderedContentControl> <HeaderedContentControl Header="가격"> <TextBox Name="priceField" Margin="10" Width="150" Height="25" VerticalContentAlignment="Center"> <TextBox.Text> <Binding Path="Price" Mode="TwoWay"> <Binding.ValidationRules> <local:PriceValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </HeaderedContentControl> <HeaderedContentControl Header="제안 만기일"> <TextBox Name="dateField" Margin="10" Width="150" Height="25" VerticalContentAlignment="Center"> <TextBox.Text> <Binding Path="OfferExpireDate" StringFormat="d"> <Binding.ValidationRules> <local:DateValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </HeaderedContentControl> <StackPanel Orientation="Horizontal"> <Button Name="submitButton" Margin="10" Width="100" Height="30" IsDefault="True" Content="제출(_S)" /> <Button Name="cancelButton" Margin="10" Width="100" Height="30" IsCancel="True" Content="취소(_C)" /> </StackPanel> <HeaderedContentControl Header="설명"> <TextBox Margin="10" Width="150" Height="30" IsReadOnly="True" VerticalContentAlignment="Center" Text="{Binding Path=Description}" /> </HeaderedContentControl> <HeaderedContentControl Header="가격"> <TextBox Margin="10" Width="150" Height="30" IsReadOnly="True" VerticalContentAlignment="Center" Text="{Binding Path=Price, StringFormat=c}" /> </HeaderedContentControl> <HeaderedContentControl Header="제안 만기일"> <TextBox Margin="10" Width="150" Height="30" IsReadOnly="True" VerticalContentAlignment="Center" Text="{Binding Path=OfferExpireDate, StringFormat=d}" /> </HeaderedContentControl> </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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
using System; using System.Windows; using System.Windows.Controls; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWnidow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWnidow() { InitializeComponent(); this.stackPanel.Loaded += stackPanel_Loaded; this.stackPanel.AddHandler ( Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(stackPanel_ValidationError) ); this.submitButton.Click += submitButton_Click; this.cancelButton.Click += cancelButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 스택 패널 로드시 처리하기 - stackPanel_Loaded(sender, e) /// <summary> /// 스택 패널 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void stackPanel_Loaded(object sender, RoutedEventArgs e) { this.stackPanel.DataContext = new PurchaseItem(); this.stackPanel.BindingGroup.BeginEdit(); } #endregion #region 스택 패널 검증 에러시 처리하기 - stackPanel_ValidationError(sender, e) /// <summary> /// 스택 패널 검증 에러시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void stackPanel_ValidationError(object sender, ValidationErrorEventArgs e) { if(e.Action == ValidationErrorEventAction.Added) { MessageBox.Show(e.Error.ErrorContent.ToString()); } } #endregion #region 제출 버튼 클릭시 처리하기 - submitButton_Click(sender, e) /// <summary> /// 제출 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void submitButton_Click(object sender, RoutedEventArgs e) { if(this.stackPanel.BindingGroup.CommitEdit()) { MessageBox.Show("항목이 제출되었습니다."); this.stackPanel.BindingGroup.BeginEdit(); } } #endregion #region 취소 버튼 클릭시 처리하기 - cancelButton_Click(sender, e) /// <summary> /// 취소 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void cancelButton_Click(object sender, RoutedEventArgs e) { this.stackPanel.BindingGroup.CancelEdit(); this.stackPanel.BindingGroup.BeginEdit(); } #endregion } } |