我正在实现一个函数“WPF Validation On StartDate and EndDate (StartDate less than Enddate)”,如果 EndDate 小于 StartDate,我在后面的代码中编写代码以引发异常,现在它可以工作了。但是我遇到了关于 StartDate 和 EndDate 文件验证的问题。由于这两个属性是我数据库中的必填字段,除非您填写这两个字段,否则应禁用“保存”按钮。但现在 StartDate 和 EndDate 文件不是强制性的。我附上我的代码。你能花几分钟看看我的代码并提供一些建议吗?非常感谢。
代码背后
public partial class OrganisationTypeSView : UserControl
{
OrganisationTypeViewModel _dataContext = new OrganisationTypeViewModel();
public OrganisationTypeSView()
{
InitializeComponent();
this.DataContext = _dataContext;
_dataContext.AccountStartDate = DateTime.Now;
_dataContext.AccountEndDate = DateTime.Now.AddMonths(1);
this.Loaded += new RoutedEventHandler(OrganisationTypeSView_Loaded);
}
void OrganisationTypeSView_Loaded(object sender, RoutedEventArgs e)
{
}
}
圣诞节
<WPFToolkit:DatePicker Grid.Column="1" Grid.Row="4" Name="dpAccStart" VerticalAlignment="Top"
SelectedDate="{Binding AccountStartDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" />
<WPFToolkit:DatePicker Grid.Column="1" Grid.Row="5" Name="dpAccEnd" VerticalAlignment="Top"
SelectedDate="{Binding AccountEndDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
视图模型
private DateTime? _AccountStartDate;
private DateTime? _AccountEndDate;
public event PropertyChangedEventHandler PropertyChanged;
[Required(ErrorMessage = "Account Start Date is a required field.")]
public DateTime? AccountStartDate
{
get { return _AccountStartDate; }
set
{
if (_AccountStartDate != DateTime.MinValue && AccountEndDate != DateTime.MinValue)
{
if (value > _AccountEndDate)
{
MessageBox.Show("Start date must be less than End date");
value = this.AccountStartDate;
}
}
_AccountStartDate = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("AccountStartDate"));
}
}
}
[Required(ErrorMessage = "Account End Date is a required field.")]
public DateTime? AccountEndDate
{
get { return _AccountEndDate; }
set
{
if (_AccountStartDate != DateTime.MinValue && AccountEndDate != DateTime.MinValue)
{
if (_AccountStartDate > value)
{
MessageBox.Show("End date must be after Start date");
value = this.AccountEndDate;
}
}
_AccountEndDate = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("AccountEndDate"));
}
}
}