简体   繁体   中英

How do you detect an automatic Month shift on the WPF Calendar control?

I am trying to create a calendar that allows the user to click and toggle selected dates. So they click each date they want to include and they are selected one at a time (without use of the ctrl or shift keys). Anyway, to accomplish this, I put two Calendars on top of each other on my control. I make one opaque and make the other one not hit test visible:

    <Calendar x:Name="_visibleCalendar" SelectionMode="MultipleRange" IsHitTestVisible="False" Margin="0,0,0,-46"/>
    <Calendar x:Name="_selectableCalendar" Opacity="0.5" SelectedDatesChanged="DateClicked" VerticalAlignment="Bottom"/>


    private void DateClicked(object sender, SelectionChangedEventArgs e)
    {
        DateTime? date = _selectableCalendar.SelectedDate;
        _selectableCalendar.SelectedDate = null;

        if (date != null)
        {
            if (_visibleCalendar.SelectedDates.Contains((DateTime) date))
            {
                _visibleCalendar.SelectedDates.Remove((DateTime) date);
            }
            else
            {
                _visibleCalendar.SelectedDates.Add((DateTime) date);
            }
        }
    }

What this does is allow the user to click on the _selectableCalendar and have their selection added to the _visibleCalendar.SelectedDates .

Kinda cool hack, if I do say so myself. It works GREAT, except for when the user changes the month on the invisible calendar.

So, what I need to know is how do I detect that the calendar has shifted to display different Month?

I have tried using DisplayDateStart and DisplayDateEnd , but these are always null.

Also, (bonus question) Is there a simple way to highlight dates on the Calendar with different colors? Like highlight each day with alternating colors? Red, Blue, Red, etc.. ?

Thanks for your help.

The naive approach

private void DateClicked(object sender, SelectionChangedEventArgs e)
{
    var dt = selectableCalendar.SelectedDate;
    if (_curr == null)
        _curr = selectableCalendar.SelectedDate;

    if (((DateTime)_curr).Month != ((DateTime)dt).Month)
    {
        _curr = dt;
        // blah
    }
}

Where DateTime? _curr; DateTime? _curr; was declared in the class scope Depending on your requirements, combine the if statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM