日历数据绑定选择错误的日期(Calendar data binding selects wrong date)

编程入门 行业动态 更新时间:2024-10-25 17:28:50
日历数据绑定选择错误的日期(Calendar data binding selects wrong date)

我在MVVM应用程序中使用常规WPF日历(System.Windows.Controls.Calendar)。 日历一次显示一个月,用户将选择一天。 日历显示下个月的几天在底部,这很好。

问题是 ,如果我从下个月(例如下个月的第二个月)选择一个日期,那么日历首先更新数据绑定与此日期,然后立即在本月1日再次更新它!

这种情况发生在我选择的下个月的所有日期。

日历的SelectedDate和DisplayDate属性是绑定到视图模型的Date属性的数据。

<Calendar SelectedDate="{Binding Date}" DisplayDate="{Binding Date}" />
 

视图模型看起来像这样

public class CalendarProblemDemoViewModel : INotifyPropertyChanged
{
    private DateTime _date;

    public CalendarProblemDemoViewModel() 
    {
        _date = DateTime.Today;
    }

    public DateTime Date
    {
        get { return _date; }
        set
        {
            _date = value;
            Debug.Write($"new date {_date}\n");
            OnPropertyChanged(nameof(Date));
        }
    }
    // Note: other code omitted, see the github project
}
 

我不明白为什么会这样?

I am using a regular WPF Calendar (System.Windows.Controls.Calendar) in an MVVM application. The calendar shows a month at a time, and the user will pick a single day. The calendar shows a few days of the next month at the bottom, which is fine.

The problem is that if I pick a date from the next month (eg the 2nd of the next month) then Calendar first updates the data binding with this date, and then immediately updates it again with the 1st of the month!

This happens for all dates in the next month that I select.

The calendar's SelectedDate and DisplayDate properties are data bound to the view model's Date property.

<Calendar SelectedDate="{Binding Date}" DisplayDate="{Binding Date}" />
 

The view model looks like this

public class CalendarProblemDemoViewModel : INotifyPropertyChanged
{
    private DateTime _date;

    public CalendarProblemDemoViewModel() 
    {
        _date = DateTime.Today;
    }

    public DateTime Date
    {
        get { return _date; }
        set
        {
            _date = value;
            Debug.Write($"new date {_date}\n");
            OnPropertyChanged(nameof(Date));
        }
    }
    // Note: other code omitted, see the github project
}
 

I don't understand why this is happening?

最满意答案

您不应将SelectedDate和DisplayDate绑定到同一属性Date 。

You should not bind both SelectedDate and DisplayDate to the same property Date.

更多推荐

本文发布于:2023-07-31 00:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340382.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   日历   错误   日期   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!