1

我正在尝试使用绑定实现对文本框的按钮单击验证。基本上,当我单击提交时,我的文本框没有变红并给我“必需”错误,这是我向其中添加文本的时候。

我是验证的新手,并且在沮丧中断断续续地看了将近一个星期。我想我的回答可能和propertychangedevent有关?但我不确定并求助于专业人士。

必须感谢所有和任何有关此的帮助。

这是我的模型类:

 public class sForms : INotifyPropertyChanged, IDataErrorInfo

{
    private string name;
    public string NAME { get { return name; } set { if (name != value) name = value.Trim(); OnPropertyChanged("NAME"); } }


    public string this[string columnName]
    {
        get
        {
            return ValidationError(columnName);
        }

    }

    public string Error { get { return null; } }


    private string ValidationError(string columnName)
    {
        string error = null;
        switch (columnName)
        {
            case "NAME":
                error = IsNameValid();
                break;
        }
        return 
            error;
    }

    static readonly string[] ValidatedProperties = { "NAME" };

    public bool IsValid
    {
        get
        {
            foreach (string property in ValidatedProperties)
            {
                if (ValidationError(property) != null)
                {
                    return
                        false;
                }
            }
            return
                true;
        }
    }

    public string IsNameValid()
    {
        if (string.IsNullOrWhiteSpace(NAME) || string.IsNullOrEmpty(NAME))
            return "Required";
        else
            return
                null;
    }


    #region Property Changed
    private void OnPropertyChanged(string propertyName)
    {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
}

这是我的按钮 + 文本框的 XAML;

        <TextBox Controls:TextBoxHelper.UseFloatingWatermark="True" 
                     Controls:TextBoxHelper.Watermark="Name *"                          
                     Grid.Column="1" Grid.Row="1"
                     Margin="0 0 2 0"         
                     Text="{Binding Path=NAME, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                     >
        <Button Content="Submit"                    
                Style="{DynamicResource SquareButtonStyle}"
                VerticalAlignment="Bottom" HorizontalAlignment="Right"
                Margin="0 0 10 0"    
                Click="Submit_Click"
                />

这是我的代码;

        public v_subsForm()
    {
        InitializeComponent();
        this.DataContext = subs;
    }

    sForms subs = new sForms();
    #region PropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Submit_Click(object sender, RoutedEventArgs e)
    {
        if (subs.IsValid)
            MessageBox.Show("True");
        else
            MessageBox.Show("False");
    }
4

1 回答 1

0

首先,假设您包含了MahApps.Metro所需的所有资源,您的代码可以正常工作。此外,您不需要INotifyPropertyChanged在代码隐藏中实现(我猜那是您的 MainWindow)。

我正在尝试使用绑定实现对文本框的按钮单击验证。

这不是如何IDataErrorInfo工作的。IDataErrorInfo定义了一个 API,绑定可以查询绑定到的对象上的错误。因此,当您的NAME属性发生更改时,绑定将查询您sForms对象上的索引器:subs["NAME"]。如果出现错误,则应用错误模板。这通常与一个提交按钮配对,该按钮的Command属性绑定到一个命令,该命令CanExecute检查错误,如果有错误,按钮被禁用(因此如果有错误,您不能提交,按钮被禁用)。

如果您想对按钮单击进行验证,则无需实现IDataErrorInfo. System.Windows.Controls.Validation类具有驱动错误呈现的附加属性:HasError, Errors, ErrorTemplate. 但是您不能像 set 那样设置Validation.HasError为 true (没有可访问的设置器)Validation.ErrorTemplate。要Validation.HasError在代码隐藏中设置,您可以使用Validation.MarkInvalid方法,但这通常不是这些事情的完成方式。这是一个简单的示例,为此,您需要在MyTextBoxName上设置属性:TextBox

private void Submit_Click(object sender, RoutedEventArgs e)
{
    if (!string.IsNullOrEmpty(MyTextBox.Text)) return;

    BindingExpression bindingExpression = 
        BindingOperations.GetBindingExpression(MyTextBox, TextBox.TextProperty);

    BindingExpressionBase bindingExpressionBase =
        BindingOperations.GetBindingExpressionBase(MyTextBox, TextBox.TextProperty);

    ValidationError validationError =
        new ValidationError(new ExceptionValidationRule(), bindingExpression);

    validationError.ErrorContent = "My error message.";

    Validation.MarkInvalid(bindingExpressionBase, validationError);
}

所以如果MyTextBox.Text是空的,就会被认为是无效的。

于 2017-11-16T13:20:13.213 回答