使用MVVM在WPF中进行动态验证?

时间:2018-09-17 05:02:02

标签: wpf validation mvvm

  

如何在wpf MVVM结构中进行文本框输入验证?

2 个答案:

答案 0 :(得分:0)

检查以下内容:https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-binding-validation并考虑以下内容:Validation.ErrorTemplate =“ {StaticResourcevalidationTemplate}”

答案 1 :(得分:0)

您应该在视图模型中实现INotifyDataErrorInfo接口:

public class ViewModel : INotifyDataErrorInfo
{
    private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();

    private string _text;
    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            //validate:
            if (_text?.Length < 3)
                _validationErrors[nameof(Text)] = "Too short...";
            ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
        }
    }

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
    public bool HasErrors => _validationErrors.Count > 0;
    public IEnumerable GetErrors(string propertyName) =>
        _validationErrors.TryGetValue(propertyName, out string error) ? new string[1] { error } : null;
}

查看:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Window>