问题
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