开发者

wpf datepicker with highlighted dates

In WPF DatePicker there's some method to high开发者_Go百科light days that is in a List like BlackoutDates but selectable?

I want to present to user the days where I have some data in my db.


Here is one way to accomplish it that takes little effort:

Inherit default styles for Calendar and CalendarDayButton and make some small changes:

<local:DateIsInListConverter x:Key="DateIsInListConverter" />

<Style x:Key="CustomCalendarDayButtonStyle" TargetType="{x:Type CalendarDayButton}" BasedOn="{StaticResource {x:Type CalendarDayButton}}">    
    <Style.Triggers>
        <DataTrigger Value="True">
            <DataTrigger.Binding>
                <MultiBinding Converter="{StaticResource DateIsInListConverter}">
                    <Binding />
                    <Binding ElementName="MyWindow" Path="HighlightedDates" />
                </MultiBinding>
            </DataTrigger.Binding>
            <Setter Property="Background" Value="Orange" />
        </DataTrigger>
    </Style.Triggers>
</Style>

<Style x:Key="CustomCalendarStyle" TargetType="{x:Type Calendar}" BasedOn="{StaticResource {x:Type Calendar}}">
    <Setter Property="CalendarDayButtonStyle" Value="{StaticResource CustomCalendarDayButtonStyle}" />
</Style>

The second Binding in the MultiBinding is to your list of interesting dates and here is the implementation of DateIsInListConverter:

public class DateIsInListConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Length < 2 || !(values[0] is DateTime) || !(values[1] is IEnumerable<DateTime>))
            return false;

        var date = (DateTime) values[0];
        var dateList = (IEnumerable<DateTime>) values[1];

        return dateList.Contains(date);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Now use the CustomCalendarStyle on a DatePicker and you are done:

<DatePicker CalendarStyle="{StaticResource CustomCalendarStyle}" />

For a complete example with a reusable HighlightDatePicker, check out my GitHub repo: https://github.com/cmyksvoll/HighlightDatePicker


You will have to override the control template of the DayButton and add a datatrigger which looks for your property to show up highlighted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜