[C#/SILVERLIGHT] Binding 태그 확장 : IDataErrorInfo 인터페이스를 이용한 바인딩 에러 처리하기
■ Binding 태그 확장에서 IDataErrorInfo 인터페이스를 이용해 바인딩 에러를 처리하는 방법을 보여준다. ▶ Product.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 |
using System; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// 제품 /// </summary> public class Product : IDataErrorInfo { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 에러 사전 /// </summary> private Dictionary<string, List<string>> errorDictionary = new Dictionary<string, List<string>>(); /// <summary> /// ID 에러 메시지 /// </summary> private const string ID_ERROR_MESSAGE = "Value cannot be less than 5."; /// <summary> /// ID 경고 메시지 /// </summary> private const string ID_WARNING_MESSAGE = "Value should not be less than 10."; /// <summary> /// 명칭 에러 메시지 /// </summary> private const string NAME_ERROR_MESSAGE = "Value must not contain any spaces."; /// <summary> /// 명칭 경고 메시지 /// </summary> private const string NAME_WARNING_MESSAGE = "Value should be 5 characters or less."; /// <summary> /// ID /// </summary> private int id; /// <summary> /// 명칭 /// </summary> private string name; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public // IDataErrorInfo #region 에러 - Error /// <summary> /// 에러 /// </summary> public string Error { get { throw new NotImplementedException(); } } #endregion // IDataErrorInfo #region 인덱서 - this[propertyName] /// <summary> /// 인덱서 /// </summary> /// <param name="propertyName">속성명</param> /// <returns>메시지</returns> public string this[string propertyName] { get { return (!this.errorDictionary.ContainsKey(propertyName) ? null : string.Join(Environment.NewLine, this.errorDictionary[propertyName])); } } #endregion #region ID - ID /// <summary> /// ID /// </summary> public int ID { get { return this.id; } set { if(IsIDValid(value) && this.id != value) { this.id = value; } } } #endregion #region 명칭 - Name /// <summary> /// 명칭 /// </summary> public string Name { get { return this.name; } set { if(IsNameValid(value) && this.name != value) { this.name = value; } } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID 무결성 여부 조사하기 - IsIDValid(id) /// <summary> /// ID 무결성 여부 조사하기 /// </summary> /// <param name="id">ID</param> /// <returns>ID 무결성 여부</returns> public bool IsIDValid(int id) { bool isValid = true; if(id < 5) { AddError("ID", ID_ERROR_MESSAGE, false); isValid = false; } else { RemoveError("ID", ID_ERROR_MESSAGE); } if(id < 10) { AddError("ID", ID_WARNING_MESSAGE, true); } else { RemoveError("ID", ID_WARNING_MESSAGE); } return isValid; } #endregion #region 명칭 무결성 여부 조사하기 - IsNameValid(name) /// <summary> /// 명칭 무결성 여부 조사하기 /// </summary> /// <param name="name">명칭</param> /// <returns>명칭 무결성 여부</returns> public bool IsNameValid(string name) { bool isValid = true; if(name.Contains(" ")) { AddError("Name", NAME_ERROR_MESSAGE, false); isValid = false; } else { RemoveError("Name", NAME_ERROR_MESSAGE); } if(name.Length > 5) { AddError("Name", NAME_WARNING_MESSAGE, true); } else { RemoveError("Name", NAME_WARNING_MESSAGE); } return isValid; } #endregion #region 에러 추가하기 - AddError(propertyName, message, isWarning) /// <summary> /// 에러 추가하기 /// </summary> /// <param name="propertyName">속성명</param> /// <param name="message">메시지</param> /// <param name="isWarning">경고 여부</param> public void AddError(string propertyName, string message, bool isWarning) { if(!this.errorDictionary.ContainsKey(propertyName)) { this.errorDictionary[propertyName] = new List<string>(); } if(!this.errorDictionary[propertyName].Contains(message)) { if(isWarning) { this.errorDictionary[propertyName].Add(message); } else { this.errorDictionary[propertyName].Insert(0, message); } } } #endregion #region 에러 제거하기 - RemoveError(propertyName, message) /// <summary> /// 에러 제거하기 /// </summary> /// <param name="propertyName">속성명</param> /// <param name="message">메시지</param> public void RemoveError(string propertyName, string message) { if(this.errorDictionary.ContainsKey(propertyName) && this.errorDictionary[propertyName].Contains(message)) { this.errorDictionary[propertyName].Remove(message); if(this.errorDictionary[propertyName].Count == 0) { this.errorDictionary.Remove(propertyName); } } } #endregion } |
▶ MainPage.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 |
using System.Windows.Controls; using System.Windows.Input; ... #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.grid.DataContext = new Product() { ID = 10, Name = "food" }; } #endregion ... #region 텍스트 박스 키 다운시 처리하기 - TextBox_KeyDown(sender, e) /// <summary> /// 텍스트 박스 키 다운시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void TextBox_KeyDown(object sender, KeyEventArgs e) { if(e.Key == Key.Enter) { (sender as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource(); } } #endregion |
▶ MainPage.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 |
<Grid x:Name="grid" xmlns:input="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input" Margin="10" Background="White"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="1" Margin="3" FontWeight="Bold" Text="Product" /> <input:Label Grid.Row="1" Grid.Column="0" Margin="3" HorizontalAlignment="Right" Target="{Binding ElementName=idTextBox}" /> <TextBox x:Name="idTextBox" Grid.Row="1" Grid.Column="1" Margin="3" MaxLength="5" Text="{Binding ID, Mode=TwoWay, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" KeyDown="TextBox_KeyDown" /> <input:DescriptionViewer Grid.Row="1" Grid.Column="2" Description="ID must be greater than 4 and should be greater than 9." /> <input:Label Grid.Row="2" Grid.Column="0" Margin="3" HorizontalAlignment="Right" Target="{Binding ElementName=nameTextBox}" /> <TextBox x:Name="nameTextBox" Grid.Row="2" Grid.Column="1" Margin="3" MaxLength="10" Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" KeyDown="TextBox_KeyDown" /> <input:DescriptionViewer Grid.Row="2" Grid.Column="2" Description="Name must not contain spaces and should be 5 characters or less." /> <input:ValidationSummary Grid.Row="3" Grid.ColumnSpan="2" Margin="3" /> </Grid> |
※