WPF文本框中的必填字段验证

时间:2017-03-12 17:20:28

标签: c# wpf validation textbox

我需要一种简单的方法来验证文本框(必填字段)。当用户按下按钮时,它应该检查所有必填字段存在。

我试过这段代码:

<Window.Resources>
    <ControlTemplate x:Key="validationTemplate">
        <DockPanel>
            <TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
            <AdornedElementPlaceholder/>
        </DockPanel>
    </ControlTemplate>
</Window.Resources>
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
    <TextBox x:Name="txtEmail1" Text="" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>

请有人建议在WPF中的文本框中进行验证。 谢谢

2 个答案:

答案 0 :(得分:1)

您应该将Text的{​​{1}}属性绑定到视图模型的属性,并在视图模型类中实现TextBox接口。

请参阅以下示例代码。

<强>代码:

IDataErrorInfo

<强> XAML:

public partial class Window3 : Window
{
    Window3ViewModel viewModel = new Window3ViewModel();
    public Window3()
    {
        InitializeComponent();
        DataContext = viewModel;
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        viewModel.Validate();
    }
}

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

    public void Validate()
    {
        bool isValid = !string.IsNullOrEmpty(_text);
        bool contains = _validationErrors.ContainsKey(nameof(Text));
        if (!isValid && !contains)
            _validationErrors.Add(nameof(Text), "Mandatory field!");
        else if (isValid && contains)
            _validationErrors.Remove(nameof(Text));

        if (ErrorsChanged != null)
            ErrorsChanged(this, new DataErrorsChangedEventArgs(nameof(Text)));
    }

    public bool HasErrors => _validationErrors.Count > 0;

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public IEnumerable GetErrors(string propertyName)
    {
        string message;
        if (_validationErrors.TryGetValue(propertyName, out message))
            return new List<string> { message };

        return null;
    }

    private string _text;
    public string Text
    {
        get { return _text; }
        set
        {
            _text = value; 
        }
    }
}

请参阅以下博文,了解有关WPF中数据验证的工作原理的更多信息。

WPF中的数据验证: https://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/

答案 1 :(得分:0)

我将向您展示如何使用IDataErrorInfo验证数据。该接口只有两个成员需要实现:

公共字符串错误{get; }-收到一条错误消息,指出此对象出了什么问题 公共字符串this [string columnName] {get; }-获取具有给定名称的属性的错误消息。 一旦实现了IDataErrorInfo,就需要在要验证的元素中将ValidatesOnDataErrors设置为true。为了简化代码示例,我在MainViewModel中实现了IDataErrorInfo,如下所示:

public class MainViewModel : BindableBase, IDataErrorInfo
{
    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; RaisePropertyChanged(); }
    }              

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; RaisePropertyChanged(); }
    }

    public string this[string columnName]
    {
        get
        {
            string error = string.Empty;

            switch (columnName)
            {
                case nameof(FirstName):
                    if (string.IsNullOrWhiteSpace(FirstName))
                        error = "First name cannot be empty.";
                    if (FirstName?.Length > 50)
                        error = "The name must be less than 50 characters.";
                    break;

                case nameof(LastName):
                    if (string.IsNullOrWhiteSpace(LastName))
                        error = "Last name cannot be empty.";
                    break;
            }

            return error;
        }
    }

    public string Error => string.Empty;
}

,然后在 TextBox 元素中,将 ValidatesOnDataError 设置为 true

<TextBox Text="{Binding FirstName, Mode=TwoWay,
            UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />