我目前正在使用MVVM和IDataErrorInfo
在一个简单的数据输入应用程序中验证TextBox
中的输入。如果用户输入非数字,我目前将TextBox
标记为红色背景:
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Pink"/>
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
但是,如果输入的值是有效输入但“超出规范”或类似值,我还要给出一个视觉指示符(橙色背景?)。对于多种“错误验证”类型,我有哪些选择?
[使用.NET Framework 4.5.1]
最佳答案
我最终实现了@Will的建议。我在每个IDataErrorInfo
错误字符串的开头插入了一个字符(在这种情况下,我只需要2个选项,所以我使用了“0”和“1”)。我创建了2个IValueConverter
;每个用于Background和ToolTip属性:
public class WarningErrorBkgdConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
char firstChar = ((string)value)[0];
if (firstChar == '0')
{
return Brushes.Pink; // Error
}
Debug.Assert(firstChar == '1', "CANTHAPPEN: Expecting 1st char of string to be 1, was " + firstChar);
return Brushes.Gold; // Warning
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
public class WarningErrorTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Just ignore the error code
return ((string)value).Substring(1);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
我从原始问题修改了
TextBox
样式以合并以下转换器:<local:WarningErrorBkgdConverter x:Key="warningErrorBkgdConverter"/>
<local:WarningErrorTextConverter x:Key="warningErrorTextConverter"/>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent,
Converter={StaticResource warningErrorBkgdConverter}}"/>
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent,
Converter={StaticResource warningErrorTextConverter}}"/>
</Trigger>
</Style.Triggers>
</Style>
然后在我的
IDataErrorInfo
实现中,使用示例:public string this[string propertyName]
{
get
{
uint testUint;
switch (propertyName)
{
case "YieldPsi1":
if (YieldPsi1 == "")
return null;
if (!UInt32.TryParse(YieldPsi1, out testUint))
return "0Must be a number";
if (testUint < 42000)
return "1Out of spec";
return null;
...
}
}
}
一切正常!