gpt4 book ai didi

c# - TimePicker(AvalonControlsLibrary)如何绑定(bind)校验?

转载 作者:太空宇宙 更新时间:2023-11-03 13:36:50 27 4
gpt4 key购买 nike

我想将自定义验证绑定(bind)到 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>

完整教程如何为 TimePicker 创建 ValidationRules

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 编写适当的绑定(bind):

<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>

关于c# - TimePicker(AvalonControlsLibrary)如何绑定(bind)校验?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18427205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com