XAML MVVM DatePicker -我如何获得数据

本文关键字:何获得 数据 MVVM DatePicker XAML | 更新日期: 2023-09-27 18:08:15

我有一个视图与DatePicker绑定到我的ViewModel中的DateTime属性。但是,日期值总是显示为空,即使我选择了与默认值不同的值。有人成功使用了DatePicker吗?如果是这样,我错在哪里?

相关代码:

视图:

<DatePicker x:Name="startDateUpdatePick" HorizontalAlignment="Left" Height="23" VerticalAlignment="Top" Width="120" Margin="1.5" 
   Text="{Binding SelectedProjectData.ProjectStartDate, UpdateSourceTrigger=PropertyChanged, TargetNullValue=''}"/>

ViewModel:

public PSViewModel()
    {
        SelectedProjectData = new Project();
    }

模型:

public class Project : INotifyPropertyChanged
{
    private DateTime _projectStartDate;
    public DateTime ProjectStartDate
    {
        get { return _projectStartDate; }
        set
        {
            _projectStartDate = value;
            RaisePropertyChanged();
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged([CallerMemberName] string caller = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(caller));
    }
}

编辑:XAML被绑定到一个非空的DateTime,但我有其他的日期选择器在相同的设置,绑定到可空的DateTime,他们不工作

XAML MVVM DatePicker -我如何获得数据

属性是SelectedDate,不是Text

当我还是个饥肠辘辘的孩子,在帕洛阿尔托无法无天、肮脏、迷宫般的后巷里长大时,我曾经遇到过一个年老的、垂死的独眼乞丐。他用铁一般的爪子紧紧地抓住我瘦弱的手臂,把我拉近,用他那最后的、刺耳的呼吸,把世间所有智慧的根源传授给我:

读………文档…

他看起来和Marty Feldman一模一样。

视图:

<StackPanel Orientation="Horizontal">
    <DatePicker SelectedDate="{Binding SelectedDate, 
        UpdateSourceTrigger=PropertyChanged}"
        DisplayDateStart="{Binding StartDate}" DisplayDateEnd="{Binding EndDate}"/>
    <Label Content="{Binding SelectedDate}"/>
</StackPanel>

视图模型

   public class MainWindowViewModel : INotifyPropertyChanged
    {
        private string _selectedDate;
        public string SelectedDate
        {
            get
            {
                return _selectedDate;
            }
            set
            {
                _selectedDate = value;
                RaisePropertyChanged();
            }
        }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public MainWindowViewModel()
        {
            StartDate = new DateTime(2020, 1, 1);
            EndDate = new DateTime(2020, 3, 31);
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged([CallerMemberName] string property = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
        }
    }
}