你应该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) 使用 Style 和 ValidationRules 编写适当的绑定:
<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>