我正在开发一个 WPF 项目,我在一个窗口上有一个 Datepicker 控件。我正在使用 MVVM 模式进行数据绑定(bind)。我已经在 Datepicker 的 SelectedDate changed 事件上设置了一个命令。问题是,例如,当我第一次更改日期时,我在命令的事件处理程序中得到 NULL。当我再次更改日期时,我会在事件处理程序中获得先前选择的日期。这是一种奇怪的行为,因为如果我不使用 WPF 命令并在代码隐藏模型中工作,就不会发生这种情况。
这是我的 DatePicker xaml 代码片段:
<DatePicker x:Name="dpEventDate" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Stretch" Margin="150,0,150,0"
VerticalAlignment="Center" SelectedDateFormat="Long"
SelectedDate="{Binding Path=., Source={x:Static sys:DateTime.Today}, StringFormat=Today is {0:dddd, MMMM dd}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedDateChanged">
<i:InvokeCommandAction Command="{Binding SelectedDateChangedCommand}"
CommandParameter="{Binding ElementName=dpEventDate, Path=SelectedDate}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DatePicker.Background>
<SolidColorBrush Color="LightYellow"></SolidColorBrush>
</DatePicker.Background>
</DatePicker>
ViewModel 类中的命令事件处理程序
get
{
return new DelegateCommand((sdate) =>
{
selectedDate = Convert.ToDateTime(sdate);
if (sdate != null)
{
//some logic here
}
}
}
set
{
SelectedDateChangedCommand = value;
RaisePropertyChangedEvent("SelectedDateChangedCommand");
}
DelegateCommand 类实现 ICommand
所以在上面的代码中,“sdate”参数总是返回之前选择的日期。如果这是我第一次更改日期,它会返回 NULL。
知道我可能做错了什么吗?
最佳答案
我不确定您试图通过将更改绑定(bind)到事件和命令来实现什么。为什么不绑定(bind) DatePicker 的 SelectedDate
属性(使用 TwoWay
模式)?目前您将其绑定(bind)到静态 DateTime.Today
。
<DatePicker x:Name="dpEventDate" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Stretch" Margin="150,0,150,0"
VerticalAlignment="Center" SelectedDateFormat="Long"
SelectedDate="{Binding MyDateTimeProperty, Mode=TwoWay}">
并且在你的 ViewModel 中有一个
private Nullable<DateTime> myDateTimeProperty = null;
public Nullable<DateTime> MyDateTimeProperty {
get {
if(myDateTimeProperty == null) {
myDateTimeProperty = DateTime.Today;
}
return myDateTimeProperty;
}
set {
myDateTimeProperty = value;
RaisePropertyChangedEvent("MyDateTimeProperty");
}
}
这样您的 ViewModel 将返回当前日期并将其设置在 DatePicker 中,如果之前的日期为 null 并且 DatePicker 已更改,它将以新的方式将其绑定(bind)回属性。
关于c# - WPF Datepicker 使用 MVVM 返回先前选择的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20659070/