Unable to refresh a CalendarView with UpdateLayout() [UWP]

a 夏天 提交于 2019-12-11 05:36:19

问题


In my UWP app, I'm trying to refresh the density bars on a calendarview if the user clicks a button, the problem is that, although calendarView.UpdateLayout(); should re-run the CalendarViewDayItemChanging event, it runs only when the CalendarView is loaded the first time. Am I doing something wrong?

 public MainPage()
        {
            this.InitializeComponent();
            densityColors.Add(Colors.Green); 
        }

      private void CalendarView_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args)
            {
                item = args.Item;
                if (item < DateTimeOffset.Now)
                {
                    item.SetDensityColors(densityColors);
                }

            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                densityColors[0]=Colors.Blue;
                calendarView.UpdateLayout();
            }

回答1:


UpdateLayout won't do anything here since there's no layout update and CalendarViewDayItemChanging is only triggered when you move to another calendar view.

In your case, you just need to manually locate all the CalendarViewDayItems and update their colors on the existing view.

First, create a little Children extension methods to help retrieve all the children of the same type.

public static class Helper
{
    public static List<FrameworkElement> Children(this DependencyObject parent)
    {
        var list = new List<FrameworkElement>();

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);

            if (child is FrameworkElement)
            {
                list.Add(child as FrameworkElement);
            }

            list.AddRange(Children(child));
        }

        return list;
    }
}

Then, simply call it in your button click handler to get all CalendarViewDayItems, loop them through and set each's color accordingly.

var dayItems = calendarView.Children().OfType<CalendarViewDayItem>();
foreach (var dayItem in dayItems)
{
    dayItem.SetDensityColors(densityColors);
}

Note you don't need to worry about new CalendarViewDayItems coming into view as they will be handled by your CalendarView_CalendarViewDayItemChanging callback.



来源:https://stackoverflow.com/questions/45736978/unable-to-refresh-a-calendarview-with-updatelayout-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!