我有两个 TextBox 控件(如下所示),我想将第一个 TextBox [x:Name="defPointFrom1Txt"
] 的文本传递到 ValidationRule [MinIntegerValidationRule
] 用于第二个 TextBox [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));
}
}
最佳答案
您不能在 Min 属性上设置绑定(bind),因为它不是依赖属性。我以前做的是在 viewmodel 上创建一个验证属性属性,它为我提供了类实例对象,然后我基于它执行我的验证。
在您的情况下,我会创建 Min 作为依赖对象。
关于c# - 将 TextBox 中的值传递给 ValidationRule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15479482/