SL4.DataAnnotations数据验证方式

没什么好说的,挺简单的,直接上Code。

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;
}
}

  

你可能感兴趣的:(Annotations)