我有同樣的任務,其中兩個日期字段必須相互協調。我還有其他業務邏輯必須與日期驗證一起實施(例如何時和何時不執行驗證)。
爲了獲得此功能,我使用了WPF DataValidation Rules。
public class ValidateDate : ValidationRule
{
public DateTime EndDate { get; set; }
/// <summary>
/// Validates date is valid
/// </summary>
/// <param name="value"></param>
/// <param name="cultureInfo"></param>
/// <returns></returns>
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
// Return if null
if (value == null)
{
return new ValidationResult(true, null);
}
DateTime t;
if (!DateTime.TryParse(value.ToString(), out t))
return new ValidationResult(false, null);
if(t == null)
{
return new ValidationResult(true, null);
}
if (t.Date < EndDate)
{
string message = "Invalid Date";
return new ValidationResult(false, message);
}
else
{
return new ValidationResult(true, null);
}
}
這是在後面的代碼中應用的綁定。
System.Windows.Data.Binding b1 = BindingOperations.GetBinding(dpMyDate,
DatePicker.SelectedDateProperty);
b1.ValidationRules.Clear(); // Clear as I reuse them
ValidateDate vd = new ValidateDate();
vd.EndDate = datePickerEndDate.SelectedDate;
b1.ValidationRules.Add(vd);
通過使用這種方法可以防止用戶的時候都像下面無效你的日期選擇器選擇一個無效的日期和設置風格。
<Style TargetType="{x:Type DatePicker}">
<Setter Property="Width" Value="110"/>
<Setter Property="Margin" Value="5" />
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Text" Value="No Date" />
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="Red" />
<Setter
Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>