当输入字符串无效时,TextBoxes中的标准行为是显示红色方块(例如,用户在数字TextBox中引入了一个字母)。当TextBox失去焦点时会发生这种情况。
我希望实现此行为:
答案 0 :(得分:0)
您在此链接中的文本框中有一个验证示例:http://www.codeproject.com/Tips/690130/Simple-Validation-in-WPF
<ControlTemplate x:Key="validationErrorTemplate">
<DockPanel>
<TextBlock Foreground="Red"
DockPanel.Dock="Top">!</TextBlock>
<AdornedElementPlaceholder
x:Name="ErrorAdorner"
></AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
public class NameValidator : ValidationRule
{
public override ValidationResult Validate
(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value == null)
return new ValidationResult(false, "value cannot be empty.");
else
{
if (value.ToString().Length > 3)
return new ValidationResult
(false, "Name cannot be more than 3 characters long.");
}
return ValidationResult.ValidResult;
}
}
<TextBox Height="23" HorizontalAlignment="Left"
Grid.Column="1" Grid.Row="0" Name="textBox1"
VerticalAlignment="Top" Width="120"
Validation.ErrorTemplate="{StaticResource validationErrorTemplate}"
>
<TextBox.Text>
<Binding Path="Name" Mode="TwoWay"
UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:NameValidator></local:NameValidator>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
答案 1 :(得分:0)
如果使用MVVM,则恢复旧值非常容易。在ViewModel的prop setter中,如果模型无效,则无法将新值设置为模型,而是调用PropertyChanged
。这将告诉绑定的视图元素调用属性getter,它将返回旧值,从而将视图元素的内容恢复为旧值。
示例(验证用户输入是int
值):
public string Number
{
get { return _model.Number.ToString(); }
set
{
if (_model.Number.ToString() != value)
{
int number;
if (int.TryParse(value, out number))
{
_model.Number = number;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Number));
}
}
}