验证没有MVVM模式的wpf

时间:2015-11-06 14:12:30

标签: c# wpf validation xaml silverlight

我正在使用WPF并使用代码隐藏文件绑定DataContext。我没有关注MVVM或任何其他模式。我想在表单中添加验证。我使用数据 System.ComponentModel.DataAnnotations 进行验证。以下是代码文件

[PropertyChanged.ImplementPropertyChanged]
public class Person : PropertyValidateModel
{
    public long Id { get; set; }

    [Required]
    public string Name { get; set; }
    public long Score { get; set; }
}


[PropertyChanged.ImplementPropertyChanged]
public abstract class PropertyValidateModel : IDataErrorInfo
{
    // check for general model error    
    public string Error { get { return null; } }

    // check for property errors    
    public string this[string columnName]
    {
        get
        {
            var validationResults = new List<ValidationResult>();

            if (Validator.TryValidateProperty(
                    GetType().GetProperty(columnName).GetValue(this)
                    , new ValidationContext(this)
                    {
                        MemberName = columnName
                    }
                    , validationResults))
                return null;

            return validationResults.First().ErrorMessage;
        }
    }
}  

我的XAML文件如下:

<Window x:Class="WPFDataContext.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel HorizontalAlignment="Left">
        <TextBox Width="100" Text="{Binding Path=Name, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
        <TextBox Width="100" Text="{Binding Path=Score, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
        <Button Name="btnSave" Click="btnSave_Click" Content="Save" ></Button>
    </StackPanel>
</Grid>

这对表单添加验证,但如果我想检查模型是否有效,那我该怎么检查?请帮助我,因为我没有获得我在MVC模式中用于ModelState.IsValid的IsValid属性。请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以使用TextBox的lostfocus事件,例如,您要对texbox进行电子邮件验证

您的XAML

<TextBox x:Name="txtEmail1" Grid.Column="1" Grid.Row="7" MaxLength="70"  Margin="0,5,5,0" Style="{StaticResource  md-3s-textbox}" HorizontalAlignment="Left"  LostFocus="TxtEmail1_LostFocus"  >

您的背后密码

 public static bool IsValidEmail( string email)
        {
            string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
            var regex = new Regex(pattern, RegexOptions.IgnoreCase);
            return regex.IsMatch(email);
        }

    private void TxtEmail1_LostFocus(object sender, RoutedEventArgs e)
    {
        if (IsValidEmail(txtEmail1.Text.ToString().Trim())==false)
        {
            txtEmail1.ToolTip = "Invalid Email";
            txtEmail1.BorderBrush= System.Windows.Media.Brushes.Red;
        }
        
    }