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

      

  • 相关阅读:
    #region...#endregion: C# syntax
    Regular Expression in C#
    北京邮电大学网络与交换技术国家重点实验室
    C#: 得到系统中的环境变量(源代码)
    Contrasting C# and Java Syntax(摘录)
    Using ZipLib to create a Zip File in C#
    SQL Server DO's and DONT's 摘录
    SQL View 的使用语法与原则
    时隔两年
    VS 里的快捷键定制
  • 原文地址:https://www.cnblogs.com/baobao2010/p/2152326.html
Copyright © 2020-2023  润新知