你應該把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)寫入適當的風格和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>
我把,但以這種方式不能使用我的自定義驗證程序。 SelectedTime =「{綁定路徑= start_time,UpdateSourceTrigger = PropertyChanged,Mode = TwoWay}」/>我無法找到如何設置validationrule內聯。 –
@LóriNóda再次檢查我的答案。 – kmatyaszek
謝謝@kmatyaszek問題在於我把Time Binger放在Timepicker標籤內而不是。再次感謝。我不知道爲什麼我沒有在你的第一個答案中看到。 –