■ IDataErrorInfo 인터페이스를 사용해 커스텀 객체에 대한 검증 로직을 구현하는 방법을 보여준다.
▶ Person.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 |
using System.ComponentModel; namespace TestProject { /// <summary> /// 사람 /// </summary> public class Person : IDataErrorInfo { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 나이 - Age /// <summary> /// 나이 /// </summary> public int Age { get; set; } #endregion #region 에러 - Error /// <summary> /// 에러 /// </summary> public string Error => null; #endregion #region 인덱서 - this[name] /// <summary> /// 인덱서 /// </summary> /// <param name="name">명칭</param> /// <returns>오류 메시지</returns> public string this[string name] { get { string result = null; if(name == "Age") { if(Age < 0 || Age > 150) { result = "Age must not be less than 0 or greater than 150."; } } return result; } } #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 |
<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"> <Window.Resources> <local:Person x:Key="PersonKey" /> <Style x:Key="ErrorTextBoxStyleKey" TargetType="TextBox"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock>Enter your age :</TextBlock> <TextBox Style="{StaticResource ErrorTextBoxStyleKey}" HorizontalAlignment="Left" Margin="0 10 0 0" Width="100" Height="25" VerticalContentAlignment="Center"> <TextBox.Text> <Binding Path="Age" Source="{StaticResource PersonKey}" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <DataErrorValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> <TextBlock Margin="0 10 0 0">Mouse-over to see the validation error message.</TextBlock> </StackPanel> </Window> |