当计算值被推送到文本框字段时,我希望进行范围规则验证,但验证仅在用户将值直接输入文本框时显示。验证不会从用户放入其他文本框的值计算中发生。如何通过自动计算动态进行验证? 我对C#和mvvm很新,所以也许我没有把它弄好。我不太了解IDataErrorInfo,所以如果可能的话我宁愿使用INotifyPropertyChanged。
private int _FIMSamlet_score;
public int FIMSamlet_score
{
get { return this._FIMSamlet_score; }
set
{
if (Int32.Parse(value.ToString()) < 18 || Int32.Parse(value.ToString()) > 126)
{ throw new ArgumentException("The value must be between 18 and 126"); }
this._FIMSamlet_score = value;
CalculateFimSamletscore();
this.OnPropertyChanged("FIMSamlet_score");
}
}
我输入值的计算方法。
private void CalculateFimSamletscore()
{
try
{
FIMSamlet_score = Convert.ToInt32(a)
+ Convert.ToInt32(b)
+ Convert.ToInt32(c)
+ Convert.ToInt32(d)
+ Convert.ToInt32(e)
+ Convert.ToInt32(f)
+ Convert.ToInt32(g)
+ Convert.ToInt32(h)
+ Convert.ToInt32(i)
+ Convert.ToInt32(j)
+ Convert.ToInt32(k)
+ Convert.ToInt32(l)
+ Convert.ToInt32(m);
}
catch (Exception)
{
}
}
XAML
<TextBox Validation.ErrorTemplate="{StaticResource validationTemplate}" Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="5" Name="fIM_samletScore" VerticalAlignment="Center" Width="150" Background="WhiteSmoke">
<TextBox.Text>
<Binding Path="FIMSamlet_score" Mode="TwoWay" ValidatesOnExceptions="true" NotifyOnValidationError="true" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule/>
<validators:FIMRangeRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我还制作了验证课
public class FIMRangeRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
return new ValidationResult(false, "Feltet må ikke være tomt. Indtast gyldig værdi.");
else
{
if ((Int32.Parse(value.ToString()) < 18) || (Int32.Parse(value.ToString()) > 126))
return new ValidationResult
(false, "Værdi udenfor gyldig interval 18-126");
}
return ValidationResult.ValidResult;
}
}
答案 0 :(得分:0)
BindingExpression中的ValidatioRule仅在绑定的目标端发生更改时触发。
在您的代码中,TextBox是目标端。这就是为什么你看不到验证结果的原因。
本教程继续提示,按代码设置验证错误。