SL4.DataAnnotations 데이터 검증 방법

8973 단어 Annotations
할 말 없어요. 아주 간단해요. 바로 코드로 가세요.
XAML:
    <Grid x:Name="LayoutRoot" Background="White"  BindingValidationError="LayoutRoot_BindingValidationError">
<StackPanel>
<Button Name="MyButton" Content="Update" Click="MyButton_Click" Width="65" Height="41"></Button>
<TextBlock Text="" Name="tbAccount" Width="50"></TextBlock>
<TextBox Width="150" Name="TxtUserName" Text="{Binding Path=UserName, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"></TextBox>

</StackPanel>
</Grid>

  
XAML.CS:
        private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Added)
(e.OriginalSource
as Control).Background = new SolidColorBrush(Colors.Yellow);

if (e.Action == ValidationErrorEventAction.Removed)
(e.OriginalSource
as Control).Background = new SolidColorBrush(Colors.White);
}

Users u
= new Users();
public MainPage()
{
InitializeComponent();
TxtUserName.DataContext
= u;
}

  
Users.CS:
        private string _UserName="";
[Required(ErrorMessage
=" ")]
[StringLength(
20,ErrorMessage=" 20 ")]
public string UserName
{
get
{
return _UserName;
}
set
{
if(_UserName != value)
Validator.ValidateProperty(value,
new ValidationContext(this,null,null){MemberName="UserName"});
_UserName
=value;
}
}

좋은 웹페이지 즐겨찾기