如何将验证绑定到TimePicker(AvalonControlsLibrary)
本文关键字:TimePicker AvalonControlsLibrary 绑定 验证 | 更新日期: 2023-09-27 18:28:52
我想将自定义验证绑定到TimePicker自定义控件,但下面的代码说"不能向TimePicker的对象类型添加内容。"。
<Controls:TimePicker Name="TimePickerEndTime"
Grid.Row="2"
Grid.Column="1"
SelectedHour="11"
SelectedMinute="20"
SelectedSecond="0"
>
<Binding Path="EndTime" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<Validators:MyCustomTimepickerValidation ErrorMessage="{DynamicResource NumberValidatorMesage}"/>
</Binding.ValidationRules>
</Binding>
</Controls:TimePicker>
您应该将Binding
放在SelectedTime
标签中:
<Controls:TimePicker Name="TimePickerEndTime"
Grid.Row="2"
Grid.Column="1"
SelectedHour="11"
SelectedMinute="20"
SelectedSecond="0"
>
<Controls:TimePicker.SelectedTime>
<Binding Path="EndTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<Validators:MyCustomTimepickerValidation ErrorMessage="{DynamicResource NumberValidatorMesage}"/>
</Binding.ValidationRules>
</Binding>
</Controls:TimePicker.SelectedTime>
</Controls:TimePicker>
如何将ValidationRules
创建为TimePicker
的完整教程
1) 创建样式以显示错误消息:
<Style x:Key="timePickerInError" TargetType="{x:Type Controls:TimePicker}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
2) 创建从ValidationRule
:继承的自定义类
public class TimeRangeRule : ValidationRule
{
private TimeSpan _min;
private TimeSpan _max;
public TimeRangeRule()
{
}
public TimeSpan Min
{
get { return _min; }
set { _min = value; }
}
public TimeSpan Max
{
get { return _max; }
set { _max = value; }
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value != null)
{
TimeSpan time = (TimeSpan)value;
if ((time < Min) || (time > Max))
{
return new ValidationResult(false,
"Please enter the time in the range: " + Min + " - " + Max + ".");
}
else
{
return new ValidationResult(true, null);
}
}
else
return new ValidationResult(true, null);
}
}
3) 使用样式和验证规则编写适当的绑定:
<Controls:TimePicker Name="TimePickerEndTime"
Style="{StaticResource timePickerInError}" >
<Controls:TimePicker.SelectedTime>
<Binding Path="EndTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<Validators:TimeRangeRule Min="10:00:00" Max="15:00:00"/>
</Binding.ValidationRules>
</Binding>
</Controls:TimePicker.SelectedTime>
</Controls:TimePicker>