我想为 xaml 中的 ValidationRule 绑定 xaml 中的附加属性或依赖属性,然后根据附加属性或依赖属性的值,我想在验证规则中做出总和决定。我找不到任何解决方案如何将可绑定值传递给验证规则。
问问题
3666 次
1 回答
2
我为您提供了一个示例代码来帮助您。我已经定义了一个 ValidationRule 来验证 texbox 用户输入。验证的类型是根据一个枚举参数的值来执行的。可用的验证类型有:用户输入不能为空,用户输入必须是数字,用户输入必须是 IP 地址。第二个参数允许指定显示的警告消息。如您所知,用于绑定目的的变量应该是 DependendyProperty,所以在这里您可以找到带有参数声明的类。
public class ValidationParams : DependencyObject
{
// Dependency Properties
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message",
typeof(string),
typeof(ValidationParams),
new FrameworkPropertyMetadata(string.Empty));
public static readonly DependencyProperty ValidationTypeProperty = DependencyProperty.Register("ValidationType",
typeof(FieldValidationRule.EnmValidationType),
typeof(ValidationParams),
new FrameworkPropertyMetadata(FieldValidationRule.EnmValidationType.FieldNotEmpty));
// Properties
[Category("Message")]
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
[Category("ValidationType")]
public FieldValidationRule.EnmValidationType ValidationType
{
get { return (FieldValidationRule.EnmValidationType)GetValue(ValidationTypeProperty); }
set { SetValue(ValidationTypeProperty, value); }
}
然后是验证规则类:
public class FieldValidationRule : ValidationRule
{
public enum EnmValidationType
{
FieldNotEmpty,
FieldNumeric,
FieldIPAddress
}
// Local variables and objects
private ValidationParams mParams = new ValidationParams();
public ValidationParams Params
{
get { return mParams; }
set { mParams = value; }
}
// Override
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
ValidationResult objResult = null;
string sValue = value as string;
objResult = new ValidationResult(true, null);
switch (Params.ValidationType)
{
case EnmValidationType.FieldNotEmpty:
if(string.IsNullOrEmpty(sValue) == true)
objResult = new ValidationResult(false, Params.Message);
break;
case EnmValidationType.FieldNumeric:
int iValue = 0;
if(int.TryParse(sValue, out iValue) == false)
objResult = new ValidationResult(false, Params.Message);
break;
case EnmValidationType.FieldIPAddress:
IPAddress objValue = IPMatrix.CreateHostAddr();
if(IPAddress.TryParse(sValue, out objValue) == false)
objResult = new ValidationResult(false, Params.Message);
break;
}
return objResult;
}
}
最后是 XAML 代码:
<TextBox Style="{DynamicResource FieldValue}" Grid.Column="1" IsReadOnly="False">
<TextBox.Text>
<Binding Source="{StaticResource XmlItemChannel}" XPath="@Name" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<data:FieldValidationRule>
<data:FieldValidationRule.Params>
<data:ValidationParams Message="{DynamicResource ERR002}" ValidationType="FieldNotEmpty" />
</data:FieldValidationRule.Params>
</data:FieldValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
您可以看到参数 Message 已绑定到资源,但您也可以经典地绑定它。
于 2011-06-20T10:24:58.903 回答