如何使用数据绑定在日期选择器中设置今天的日期



当前我使用的是日期选择器:

<DatePicker Name="dpEmailConfirmed1" Grid.Row="1" Grid.Column="3" SelectedDate="{Binding EmailConfirmation}" Margin="5"/>

现在我想将日期选择器设置为今天的默认日期。

到目前为止,我读到的所有文章都在使用"选择日期";用于设置。但在我的情况下,我使用它与模型绑定,以获得选定的日期。

我能换一种方式吗?

我已经有了

<my:DatePicker DisplayDate="{x:Static sys:DateTime.Now}"/>

dpEmailSent1.Text = DateTime.Now.Date.ToString();

dpEmailSent1.DisplayDate = DateTime.Now.Date.ToString();

SelectedDate属性的绑定是正确的。不要在XAML中设置默认值,而是将其分配给视图模型中的绑定EmailConfirmation属性,例如在其构造函数中:

public class MyEmailViewModel : INotifyPropertyChanged
{
public MyEmailViewModel()
{
EmailConfirmation = DateTime.Today;
}
private DateTime _emailConfirmation;
public DateTime EmailConfirmation
{
get => _emailConfirmation;
set
{
if (_emailConfirmation.Equals(value))
return;
_emailConfirmation = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// ...other view model code.
}

由于要应用今天的日期,因此可以使用DateTime.Today而不是DateTime.Now来重置实例的时间组件。

也不要忘记实现INotifyPropertyChanged,例如,像上面的例子一样,否则对属性的更改将不会反映在用户界面中。

最新更新