■ ValidationRule 클래스를 사용해 바인딩 항목을 검증하는 방법을 보여준다.
▶ DateAndPriceRule.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.Globalization; using System.Windows.Controls; using System.Windows.Data; namespace TestProject { /// <summary> /// 일자/가격 규칙 /// </summary> public class DateAndPriceRule : 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 offerExpiresObject; bool priceResult = bindingGroup.TryGetValue(item, "Price" , out priceObject ); bool offerExpiresResult = bindingGroup.TryGetValue(item, "OfferExpires", out offerExpiresObject); if(!priceResult || !offerExpiresResult) { return new ValidationResult(false, "Properties not found"); } double price = (double)priceObject; DateTime offerExpires = (DateTime)offerExpiresObject; if(price > 100) { if(offerExpires < DateTime.Today + new TimeSpan(7, 0, 0, 0)) { return new ValidationResult(false, "Items over $100 must be available for at least 7 days."); } } return ValidationResult.ValidResult; } #endregion } } |
▶ FutureDateRule.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 |
using System; using System.Globalization; using System.Windows.Controls; namespace TestProject { /// <summary> /// 미래 일자 규칙 /// </summary> internal class FutureDateRule : 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, "Value is not a valid date."); } return DateTime.Now.Date > date ? new ValidationResult(false, "Please enter a date in the future.") : ValidationResult.ValidResult; } #endregion } } |
▶ PositivePriceRule.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 |
using System; using System.Globalization; using System.Windows.Controls; namespace TestProject { /// <summary> /// 양수 가격 규칙 /// </summary> public class PositivePriceRule : 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, "Price must be positive."); } return ValidationResult.ValidResult; } catch(Exception) { return new ValidationResult(false, "Price must be a number."); } } #endregion } } |
▶ PurchaseItem.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 |
using System; using System.ComponentModel; namespace TestProject { /// <summary> /// 구매 항목 /// </summary> public class PurchaseItem : INotifyPropertyChanged, IEditableObject { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 속성 변경시 - PropertyChanged /// <summary> /// 속성 변경시 /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Struct ////////////////////////////////////////////////////////////////////////////////////////// Private #region 항목 데이터 - ItemData /// <summary> /// 항목 데이터 /// </summary> private struct ItemData { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Internal #region Field /// <summary> /// 설명 /// </summary> internal string Description; /// <summary> /// 제안 만기일 /// </summary> internal DateTime OfferExpires; /// <summary> /// 가격 /// </summary> internal double Price; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Internal #region 새 항목 구하기 - GetNewItem() /// <summary> /// 새 항목 구하기 /// </summary> /// <returns>새 항목</returns> internal static ItemData GetNewItem() { ItemData data = new ItemData { Description = "New item", Price = 0, OfferExpires = DateTime.Now + new TimeSpan(7, 0, 0, 0) }; return data; } #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 복사 데이터 /// </summary> private ItemData copyData = ItemData.GetNewItem(); /// <summary> /// 현대 데이터 /// </summary> private ItemData currentData = ItemData.GetNewItem(); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 설명 - Description /// <summary> /// 설명 /// </summary> public string Description { get { return this.currentData.Description; } set { if(this.currentData.Description != value) { this.currentData.Description = value; FirePropertyChangedEvent("Description"); } } } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> public double Price { get { return this.currentData.Price; } set { if(this.currentData.Price != value) { this.currentData.Price = value; FirePropertyChangedEvent("Price"); } } } #endregion #region 제안 만기일 - OfferExpires /// <summary> /// 제안 만기일 /// </summary> public DateTime OfferExpires { get { return this.currentData.OfferExpires; } set { if(value != this.currentData.OfferExpires) { this.currentData.OfferExpires = value; FirePropertyChangedEvent("OfferExpires"); } } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - PurchaseItem() /// <summary> /// 생성자 /// </summary> public PurchaseItem() { } #endregion #region 생성자 - PurchaseItem(description, price, offerExpires) /// <summary> /// 생성자 /// </summary> /// <param name="description">설명</param> /// <param name="price">가격</param> /// <param name="offerExpires">제안 만기일</param> public PurchaseItem(string description, double price, DateTime offerExpires) { Description = description; Price = price; OfferExpires = offerExpires; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 편집 시작하기 - BeginEdit() /// <summary> /// 편집 시작하기 /// </summary> public void BeginEdit() { this.copyData = this.currentData; } #endregion #region 편집 취소하기 - CancelEdit() /// <summary> /// 편집 취소하기 /// </summary> public void CancelEdit() { this.currentData = this.copyData; FirePropertyChangedEvent(""); } #endregion #region 편집 종료하기 - EndEdit() /// <summary> /// 편집 종료하기 /// </summary> public void EndEdit() { this.copyData = ItemData.GetNewItem(); } #endregion #region 문자열 구하기 - ToString() /// <summary> /// 문자열 구하기 /// </summary> /// <returns>문자열</returns> public override string ToString() => $"{Description}, {Price:c}, {OfferExpires:D}"; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 속성 변경시 이벤트 발생시키기 - FirePropertyChangedEvent(propertyName) /// <summary> /// 속성 변경시 이벤트 발생시키기 /// </summary> /// <param name="propertyName">속성명</param> private void FirePropertyChangedEvent(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #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 |
<Window x:Class="TestProject.MainWindow" 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="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel Name="stackPanel" Margin="10" Validation.Error="stackPanel_ValidationError"> <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="10 0 0 0" ContentSource="Content" /> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="Button"> <Setter Property="Margin" Value="10" /> <Setter Property="Width" Value="100"/> <Setter Property="Height" Value="30" /> </Style> </StackPanel.Resources> <StackPanel.BindingGroup> <BindingGroup NotifyOnValidationError="True"> <BindingGroup.ValidationRules> <local:DateAndPriceRule ValidationStep="ConvertedProposedValue" /> </BindingGroup.ValidationRules> </BindingGroup> </StackPanel.BindingGroup> <TextBlock Margin="10" TextWrapping="Wrap"> This sample demonstrates how to validate an object by checking multiple properties in a ValidationRule. When a ValidationRule is added to a BindingGroup, the rule can get the properties of the source item in the Validate method. <LineBreak/><LineBreak/> This sample checks that if an item costs more than 100 dollars, the item is available for at least 7 days. </TextBlock> <TextBlock Margin="10" FontWeight="Bold" Text="Enter an item for sale" /> <HeaderedContentControl Header="Description"> <TextBox Width="150" Text="{Binding Path=Description, Mode=TwoWay}" /> </HeaderedContentControl> <HeaderedContentControl Header="Price"> <TextBox Width="150"> <TextBox.Text> <Binding Path="Price" Mode="TwoWay" > <Binding.ValidationRules> <local:PositivePriceRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </HeaderedContentControl> <HeaderedContentControl Header="Date Offer Ends"> <TextBox Width="150" > <TextBox.Text> <Binding Path="OfferExpires" StringFormat="d"> <Binding.ValidationRules> <local:FutureDateRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </HeaderedContentControl> <StackPanel Orientation="Horizontal"> <Button Name="submitButton" IsDefault="True"> _Submit </Button> <Button Name="cancelButton" IsCancel="True"> _Cancel </Button> </StackPanel> <HeaderedContentControl Header="Description"> <TextBlock Width="150" Text="{Binding Path=Description}" /> </HeaderedContentControl> <HeaderedContentControl Header="Price"> <TextBlock Width="150" Text="{Binding Path=Price, StringFormat=c}" /> </HeaderedContentControl> <HeaderedContentControl Header="Date Offer Ends"> <TextBlock Width="150" Text="{Binding Path=OfferExpires, 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 |
using System.Windows; using System.Windows.Controls; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); this.stackPanel.Loaded += stackPanel_Loaded; 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 Submit 버튼 클릭시 처리하기 - submitButton_Click(sender, e) /// <summary> /// Submit 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void submitButton_Click(object sender, RoutedEventArgs e) { if(this.stackPanel.BindingGroup.CommitEdit()) { MessageBox.Show("Item submitted"); this.stackPanel.BindingGroup.BeginEdit(); } } #endregion #region Cancel 버튼 클릭시 처리하기 - cancelButton_Click(sender, e) /// <summary> /// Cancel 버튼 클릭시 처리하기 /// </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 } } |