我有一些TextBox"受控制"通过范围验证器:
public class RangeValidator : ValidationRule
{
public int Min { get; set; }
public int Max { get; set; }
public bool CheckZeroValue { get; set; }
public RangeValidator() { }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int Value = 0;
try
{
if (((string)value).Length > 0)
Value = Int32.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, "Wrong Character - " + e.Message);
}
if (CheckZeroValue && (Value == 0))
return new ValidationResult(true, null);
if ((Value < Min) || (Value > Max))
{
return new ValidationResult(false, String.Format("The range is: {0} - {1}", Min, Max));
}
else
{
return new ValidationResult(true, null);
}
}
}
现在,我想做的是当用户更改文本框值时,另一个文本框的最小值会相应地改变,就像这样......
<TextBox Grid.Row="1" Grid.Column="1" MaxLength="2" Name="FLD_OPEN_SNS_MIN">
<TextBox.Text>
<Binding Path='Fields[(local:EFields)FLD_OPEN_SNS_MIN]'
UpdateSourceTrigger="PropertyChanged"
NotifyOnValidationError="True"
ValidatesOnExceptions="True" >
<Binding.ValidationRules>
<local:RangeValidator Min="10" Max="50"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBox Grid.Row="2" Grid.Column="1" MaxLength="3" Margin="5" >
<TextBox.Text>
<Binding Path='Fields[(local:EFields)FLD_OPEN_SNS_MAX]'
UpdateSourceTrigger="PropertyChanged"
NotifyOnValidationError="True"
ValidatesOnExceptions="True" >
<Binding.ValidationRules>
<local:RangeValidator Min="{Binding ElementName=FLD_OPEN_SNS_MIN,
Path=Text
Converter={StaticResource StringToIntConverter}}" Max="50"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
这不起作用,因为ValidationRule类不是DependencyObject。 有没有办法在不使用代码的情况下实现这一目标?
答案 0 :(得分:1)
这不起作用,因为ValidationRule类不是DependencyObject。有没有办法在不使用代码的情况下实现这一目标?
您可以创建一个派生类,该派生类派生自DependencyObject并公开依赖项属性。有关详细信息,请参阅以下TechNet文章。
WPF:将数据绑定值传递给验证规则: here it is on pastebin.com
<TextBox Grid.Row="2" Grid.Column="1" MaxLength="3" Margin="5">
<TextBox.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding ElementName=FLD_OPEN_SNS_MIN}"/>
</TextBox.Resources>
<TextBox.Text>
<Binding Path='Fields[(local:EFields)FLD_OPEN_SNS_MAX]'
UpdateSourceTrigger="PropertyChanged"
NotifyOnValidationError="True"
ValidatesOnExceptions="True" >
<Binding.ValidationRules>
<local:RangeValidator Max="50"/>
<local:RangeValidator.Wrapper>
<local:Wrapper Min="{Binding Path=Text, Source={StaticResource proxy}, Converter={StaticResource StringToIntConverter}}"/>
</local:RangeValidator.Wrapper>
</Binding.ValidationRules>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>