■ BindingExpression 클래스의 ValidateWithoutUpdate/UpdateSource 메소드를 사용해 바인딩을 검증하는 방법을 보여준다.
▶ CallNumberValidationRule.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 |
using System.Globalization; using System.Windows.Controls; namespace TestProject { /// <summary> /// 호출 번호 검증 규칙 /// </summary> public class CallNumberValidationRule : 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) { string callNumber = (string)value; int dotIndex = callNumber.IndexOf("."); if(dotIndex == -1 || dotIndex == 0) { return new ValidationResult ( false, "호출 번호에는 문자 뒤에 마침표(.)가 와야합니다." ); } string remaingString = callNumber.Substring(dotIndex + 1); if(remaingString.Length != 6) { return new ValidationResult ( false, "호출 번호는 마침표(.) 뒤에 6자이어야 합니다." ); } 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 |
<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="BindingExpression 클래스 : ValidateWithoutUpdate/UpdateSource 메소드를 사용해 바인딩 검증하기" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <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> <HeaderedContentControl Header="제목"> <TextBox Width="250" Height="25" VerticalContentAlignment="Center" Text="{Binding Path=Title, Mode=TwoWay}" /> </HeaderedContentControl> <HeaderedContentControl Header="호출 번호"> <TextBox Name="callNumberTextBox" Width="250" Height="25" VerticalContentAlignment="Center"> <TextBox.Text> <Binding Path="CallNumber" Mode="TwoWay" NotifyOnValidationError="True" UpdateSourceTrigger="Explicit"> <Binding.ValidationRules> <local:CallNumberValidationRule ValidationStep="ConvertedProposedValue" /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </HeaderedContentControl> <HeaderedContentControl Header="마감일"> <TextBox Width="250" Height="25" VerticalContentAlignment="Center" Text="{Binding Path=DueDate, StringFormat=d, Mode=TwoWay}" /> </HeaderedContentControl> <Button Name="submitButton" HorizontalAlignment="Left" Margin="10" Width="100" Height="30"> 제출하기 </Button> <HeaderedContentControl Header="제목"> <TextBox Width="250" Height="25" IsReadOnly="True" VerticalContentAlignment="Center" Text="{Binding Path=Title, Mode=TwoWay}" /> </HeaderedContentControl> <HeaderedContentControl Header="호출 번호"> <TextBox Width="250" Height="25" IsReadOnly="True" VerticalContentAlignment="Center" Text="{Binding CallNumber}" /> </HeaderedContentControl> <HeaderedContentControl Header="마감일"> <TextBox Width="250" Height="25" IsReadOnly="True" VerticalContentAlignment="Center" Text="{Binding Path=DueDate, StringFormat=d, Mode=TwoWay}" /> </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 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); TestDataItem item = new TestDataItem ( "제목을 입력해 주시기 바랍니다.", "호출 번호를 입력해 주시기 바랍니다.", DateTime.Now + new TimeSpan(14, 0, 0, 0) ); this.callNumberTextBox.LostFocus += callNumberTextBox_LostFocus; this.callNumberTextBox.AddHandler ( Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(callNumberTextBox_ValidationError) ); this.submitButton.Click += submitButton_Click; DataContext = item; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 호출 번호 텍스트 박스 포커스 상실시 처리하기 - callNumberTextBox_LostFocus(sender, e) /// <summary> /// 호출 번호 텍스트 박스 포커스 상실시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void callNumberTextBox_LostFocus(object sender, RoutedEventArgs e) { BindingExpression bindingExpression = this.callNumberTextBox.GetBindingExpression(TextBox.TextProperty); bindingExpression.ValidateWithoutUpdate(); } #endregion #region 호출 번호 텍스트 박스 검증 에러시 처리하기 - callNumberTextBox_ValidationError(sender, e) /// <summary> /// 호출 번호 텍스트 박스 검증 에러시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void callNumberTextBox_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) { BindingExpression bindingExpression = this.callNumberTextBox.GetBindingExpression(TextBox.TextProperty); bindingExpression.UpdateSource(); } #endregion } } |