获取DataPicker值MVVM

时间:2018-05-03 16:19:29

标签: c# wpf

public DateTime TheDate
    {
        get { return _TheDate; }
        set
        {

                _TheDate= value;
                NotifyOfPropertyChange("TheDate");

        }

XAML:

<DatePicker  Text="{Binding TheDate}" Grid.Row="4" Grid.Column="1" Width="150" materialDesign:HintAssist.Hint="Put Date here"/>

我将01/01/0001作为默认值。如果我尝试从DatePicker更改它,除了年份之外一切都会改变(仍为0001)。如果我尝试检索该值,即使DatePicker显示日期和月份已更改为其他值,我仍将获得01/01/0001

2 个答案:

答案 0 :(得分:0)

首先,您应该使用dependency property。这使得将属性绑定到DateTimePicker非常简单。

public DateTime SelectedDateTime
{
    get { return (DateTime)GetValue(SelectedDateTimeProperty); }
    set { SetValue(SelectedDateTimeProperty, value); }
}

// Using a DependencyProperty as the backing store for SelectedDateTime. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedDateTimeProperty =
DependencyProperty.Register("SelectedDateTime", typeof(DateTime), typeof(YourModel), new PropertyMetadata(DateTime.Now));

现在,如果您查看DependencyProperty.Register()的参数,您可以看到,有一个名为PropertyMetadata的参数(第3个)。这是您的默认值。就我而言,它是DateTime.Now

然后,您可以像所有其他属性

一样将您的依赖项属性绑定到DateTimePicker
<DatePicker SelectedDate="{Binding SelectedDateTime}"/>

希望这有帮助。

答案 1 :(得分:0)

SelectedValue的{​​{1}}属性绑定到您的源属性:

DatePicker

...并将视图模型中<DatePicker SelectedDate="{Binding TheDate}" ... /> 字段的值设置为您要显示的默认日期:

_TheDate