当我的文本框为空/ null时,我需要显示“必需”。
在我的xaml中:
<TextBox Name="txtLastName" Grid.Column="1" Grid.Row="1" Margin="3">
<TextBox.Text>
<Binding Path="LastName">
<Binding.ValidationRules>
<validators:Contractor
MinimumLength="1"
MaximumLength="40"
ErrorMessage="Required" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
在我班上:
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyPropertyChanged("LastName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private int _minimumLength = -1;
private int _maximumLength = -1;
private string _errorMessage;
public int MinimumLength
{
get { return _minimumLength; }
set { _minimumLength = value; }
}
public int MaximumLength
{
get { return _maximumLength; }
set { _maximumLength = value; }
}
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
public override ValidationResult Validate(object value,CultureInfo cultureInfo)
{
ValidationResult result = new ValidationResult(true, null);
string inputString = (value ?? string.Empty).ToString();
if (inputString.Length < this.MinimumLength || value==null ||
(this.MaximumLength > 0 &&
inputString.Length > this.MaximumLength))
{
result = new ValidationResult(false, this.ErrorMessage);
}
return result;
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
我得到的是当数据为空/空时文本框变为红色边框,我无法看到“必需”错误消息,有什么想法吗?
答案 0 :(得分:4)
(当附加属性TextBox
为真时,红色边框是Validation.HasError
的默认行为。
为了显示错误消息,您必须通过绑定到Validation.Errors
来自己完成
。 Validation.Errors
是应用于TextBox
的每个验证程序的错误列表。
现在,在您的情况下,您只有一个验证器,以便获取您需要绑定到Validation.Errors[0].ErrorContent
的错误消息
示例
<StackPanel Orientation="Horizontal">
<TextBox Name="txtLastName" Width="100">
<TextBox.Text>
<Binding Path="LastName">
<Binding.ValidationRules>
<validators:Contractor
MinimumLength="1"
MaximumLength="40"
ErrorMessage="Required" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<!-- Show error message tot the right of the TextBox-->
<TextBlock Text="{Binding (Validation.Errors)[0].ErrorContent, ElementName=txtLastName}"/>
</StackPanel>