我有两个 TextBox 控件(如下),并希望将第一个 TextBox [] 的文本传递给第二个 TextBox [ x:Name="defPointFrom1Txt"
] 的 ValidationRule [ MinIntegerValidationRule
],x:Name="defPointTo1Txt"
而不是当前值 1。我可以在代码中通过命名当第一个 TextBox 中的值更改时,验证规则和设置基于事件。但是,有没有办法在 XAML 中执行此操作以将所有验证逻辑保存在一个位置?
<TextBox x:Name="defPointFrom1Txt" Grid.Row="2" Grid.Column="1" Style="{StaticResource lsDefTextBox}"
Text="{Binding Path=OffensePointsAllowed[0].From}" IsEnabled="False"/>
<TextBox x:Name="defPointTo1Txt" Grid.Row="2" Grid.Column="2" Style="{StaticResource lsDefTextBox}"
LostFocus="defPointTo1Txt_LostFocus">
<TextBox.Text>
<Binding Path="OffensePointsAllowed[0].To" StringFormat="N1">
<Binding.ValidationRules>
<gui:MinIntegerValidationRule Min="1"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
为了完整性,我的验证规则代码如下。
public class IntegerValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
float controlValue;
try
{
controlValue = int.Parse(value.ToString());
}
catch (FormatException)
{
return new ValidationResult(false, "Value is not a valid integer.");
}
catch (OverflowException)
{
return new ValidationResult(false, "Value is too large or small.");
}
catch (ArgumentNullException)
{
return new ValidationResult(false, "Must contain a value.");
}
catch (Exception e)
{
return new ValidationResult(false, string.Format("{0}", e.Message));
}
return ValidationResult.ValidResult;
}
}
public class MinIntegerValidationRule : IntegerValidationRule
{
public int Min { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
ValidationResult retValue = base.Validate(value, cultureInfo);
if (retValue != ValidationResult.ValidResult)
{
return retValue;
}
else
{
float controlValue = int.Parse(value.ToString());
if (controlValue < Min)
{
return new ValidationResult(false, string.Format("Please enter a number greater than or equal to {0}.",Min));
}
else
{
return ValidationResult.ValidResult;
}
}
}
}
更新:
为了响应以下答案,我正在尝试创建一个 DependencyObject。我这样做如下,但不知道如何在 ValidationRule 代码中使用它(甚至不知道我正确地创建了它)。
public abstract class MinDependencyObject : DependencyObject
{
public static readonly DependencyProperty MinProperty =
DependencyProperty.RegisterAttached(
"Min", typeof(int),
typeof(MinIntegerValidationRule),
new PropertyMetadata(),
new ValidateValueCallback(ValidateInt)
);
public int Min
{
get { return (int)GetValue(MinProperty); }
set { SetValue(MinProperty, value); }
}
private static bool ValidateInt(object value)
{
int test;
return (int.TryParse(value.ToString(),out test));
}
}