You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WPF日历控件的多个选中日期绑定到ViewModel属性?

WPF日历多选日期绑定到ViewModel解决方案

问题诊断

你当前的代码存在两个核心问题:

  • 日历控件启用多选模式后,应绑定SelectedDates属性而非SelectedDate(后者仅适用于单日期选择场景)
  • ViewModel未实现INotifyPropertyChanged接口,且集合类型不符合WPF绑定的最佳实践要求

修正后的XAML代码

将Calendar的绑定目标改为SelectedDates,并设置双向绑定模式:

<Calendar
    SelectionMode="MultipleRange"  
    DisplayDateStart="3/1/2022"
    DisplayDateEnd="3/31/2022"
    FirstDayOfWeek="Monday"
    IsTodayHighlighted="True"
    SelectedDates="{Binding DateList, Mode=TwoWay}"        
/>

修正后的ViewModel代码

  1. 实现INotifyPropertyChanged接口,确保属性变更能同步通知UI
  2. 将集合类型替换为ObservableCollection<DateTime>(WPF绑定的首选集合类型,自动支持元素变更通知)
namespace MVVMPractice.ViewModel
{
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;

    public class PersonViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<DateTime> _dateList;
        public ObservableCollection<DateTime> DateList
        {
            get => _dateList;
            set
            {
                _dateList = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

关键说明

  • SelectedDates是日历多选模式的专属绑定属性,类型为SelectedDatesCollection,可直接与ObservableCollection<DateTime>双向绑定
  • INotifyPropertyChanged是MVVM模式中ViewModel的基础接口,必须实现才能保证UI与ViewModel的数据同步
  • 若坚持使用List<DateTime>,需手动处理集合变更通知,但ObservableCollection是WPF原生支持的类型,使用更便捷

内容的提问来源于stack exchange,提问作者Gourav Srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:55:34