在按钮单击事件上实现IDataErrorInfo



我正在尝试使用绑定对文本框的按钮点击进行验证。基本上,当我点击提交时,我的文本框不会变成红色并给我"必需"的错误,而是当我添加文本到它时。

我是一个刚开始验证的人,在沮丧中断断续续地看了将近一周。我想我的答案可能与房地产改革有关?但我不确定,只能求助于专业人士。

我们将不胜感激在这方面提供的一切帮助。

这是我的模型类:

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");
}

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

我正在尝试使用绑定对文本框的按钮点击进行验证。

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

如果您想在单击按钮时进行验证,则不需要实现IDataErrorInfoSystem.Windows.Controls.Validation类具有驱动错误显示的附加属性:HasErrorErrorsErrorTemplate。但是,您不能像设置Validation.ErrorTemplate那样仅将Validation.HasError设置为true(没有可访问的setter)。要在代码后面设置Validation.HasError,可以使用Validation.MarkInvalid方法,但通常不是这样做的。这里有一个快速的例子,为了实现这一点,您需要将TextBox上的Name属性设置为MyTextBox:

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为空,它将被视为无效。

最新更新