public PilingLateralMenu()
{
...
_datepickers.setQuickDate(DatePickersRange.QuickDateRange.PAST_WEEK);
_datepickers._datesChanged += onDatesChanged;
}
在此构造函数中,调用setQuickDate将触发_datesChanged事件。事实是,我不希望在构造函数中调用onDatesChanged,所以我只能在之后订阅它。
但onDatesChanged仍被调用,我不明白为什么?是否有一些事件队列仅在构造函数完成后才使用? 我怎么能避免这个?
事件触发类中的相关位(_datepickers):
public delegate void DatesChangeEventHandler(DateTime from, DateTime to);
public event DatesChangeEventHandler _datesChanged;
public DatePickersRange()
{
...
_dateFrom.SelectedDateChanged += onSelectedDatesChange;
_dateTo.SelectedDateChanged += onSelectedDatesChange;
_quickDateSelection.SelectionChanged += onQuickDateSelectionChange;
Content = _layout;
}
// Select a "quick date"
public void setQuickDate(QuickDateRange dateRange)
{
_quickDateSelection.SelectedIndex = (int)dateRange;
}
// "Quick date" selected, selecting corresponding dates in the regular datepickers
private void onQuickDateSelectionChange(object sender, SelectionChangedEventArgs e)
{
_quickDateSelection.IsDropDownOpen = false;
DateTime now = DateTime.Now.Date;
// This seems to be still called and might be the same issue, resulting in the event being fired twice
_dateTo.SelectedDateChanged -= onSelectedDatesChange;
_dateTo.SelectedDate = new DateTime?(now.AddDays(1));
_dateTo.SelectedDateChanged += onSelectedDatesChange;
switch ((QuickDateRange) (sender as ComboBox).SelectedIndex)
{
case QuickDateRange.TODAY:
_dateFrom.SelectedDate = new DateTime?(now);
break;
case QuickDateRange.PAST_TWO_DAYS:
_dateFrom.SelectedDate = new DateTime?(now.AddDays(-1));
break;
case QuickDateRange.PAST_WEEK:
_dateFrom.SelectedDate = new DateTime?(now.AddDays(-7));
break;
case QuickDateRange.PAST_MONTH:
_dateFrom.SelectedDate = new DateTime?(now.AddDays(-30));
break;
}
}
private void onSelectedDatesChange(object sender, EventArgs e)
{
if (_dateFrom.SelectedDate != null && _dateTo.SelectedDate != null)
{
DateTime from = (DateTime)_dateFrom.SelectedDate;
DateTime to = (DateTime)_dateTo.SelectedDate;
if (from > to)
return;
if (_datesChanged != null)
_datesChanged(from, to);
}
}