2

什么时候日期时间?我的 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));
    }
}

如果我可以提供更多细节来帮助您帮助我,请告诉我。

4

1 回答 1

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;
    }
}
于 2012-05-18T15:34:40.093 回答