c# - WPF Datepicker 使用 MVVM 返回先前选择的日期

标签 c# wpf mvvm datepicker

我正在开发一个 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/

相关文章:

c# - 文本框的 Razor MVC 数字格式

c# - 从程序集中加载 ResourceDictionary

c# - 从 WPF 窗口获取 System.Windows.Forms.IWin32Window

c# - 私有(private)方法和属性与公共(public)方法和属性在 C#(和其他语言)中的内存占用

c# - 解析具有许多(数百万)行的大型(> 4GB)文本文件的最佳(速度)方式是什么?

c# - 如何使用名称访问 SqlParameter 数组

c# - 找不到 View 模型的 View

c# - MainWindow.xaml 打开时运行项目花费的时间太长 - WPF

mvvm - kendo 将 HTML 元素绑定(bind)到网格选定的行/数据项

design-patterns - MVVM是哪种类型的设计模式?