当DateTime?我的DateTimePicker控件的源更改为null,我想选择另一个日期,日历下拉默认为选定的上个月和年份。
我正在使用DateTimePicker进行DOB,因此月份和年份会有很大差异,我宁愿将日历重置为数据源更改为null时的当前月份和年份。来自WPFToolkit的DateTimePicker执行此操作,但我不想要它带有的微调器或时间选择,并且找不到隐藏它们的方法。
我正在使用MVVM设计模式,并希望避免立即代码隐藏。
来自视图的XAML:
<DatePicker Height="25" HorizontalAlignment="Left" Margin="53,47,0,0"
Name="dpEventDate" VerticalAlignment="Top" Width="115"
SelectedDate="{Binding EventItem.BirthDate, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />
来自视图模型的C#:(事件是我在模型中创建的类)
private Event _eventItem;
public event PropertyChangedEventHandler PropertyChanged;
public RelayCommand CreateCommand { get; private set; }
public Event EventItem
{
get { return _eventItem; }
set { _eventItem = value; OnPropertyChanged("EventItem"); }
}
public MainViewModel()
{
EventItem = new Event();
CreateCommand = new RelayCommand(CreateEvent);
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
如果我能提供更多细节来帮助您,请告诉我。
答案 0 :(得分:1)
根据Adam的建议,以下是视图模型中的代码,它帮助我重置了DateTimePicker的日历显示:
private Event _eventItem;
private DateTime? _viewDate;
public event PropertyChangedEventHandler PropertyChanged;
public RelayCommand CreateCommand { get; private set; }
public Event EventItem
{
get { return _eventItem; }
set { _eventItem = value; OnPropertyChanged("EventItem"); }
}
// Decoy DateTime property
public DateTime? ViewDate
{
get { return _viewDate; }
set
{
_viewDate = value;
EventItem.EventDate = _viewDate; // Update the source
OnPropertyChanged("ViewDate");
}
}
public MainViewModel()
{
EventItem = new Event();
CreateCommand = new RelayCommand(CreateEvent);
}
private void CreateEvent()
{
ViewDate = DateTime.Today; // Important for resetting the calendar display
// Save input and set EventItem to new event for a clean slate
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
// Important if you want your DatePicker control to be empty
if(name.Equals("ViewDate") && DateTime.Today.Equals(ViewDate))
{
ViewDate = null;
}
}