2017-02-07 45 views
0

我正在使用通用Windows平台构建Windows Phone 10应用程序。在我的应用程序中,我有一个标准的CalendarView,我想在有日期的日期显示密度颜色。这个想法是在页面加载后立即加载日历,发出API请求,并在成功的数据检索后让CalendarView刷新它的UI,以便调用CalendarViewDayItemChanging事件。从那里我可以设置我的密度颜色的细胞有事件。UWP CalendarView更新命令

我几乎一切正常,除了一部分。当日历第一次加载时,我将它的最小/最大日期范围设置为当前月份,这样我们一次只能看到一个月。这会导致日历的UI按预期进行刷新。但是,如果我尝试再次将最小/最大日期范围设置为相同日期,那么API请求完成后,日历不会刷新其UI。由于这个原因,我无法强制CalendarView刷新它的UI。我已经尝试重置最小/最大日期范围,并且我试图将日历的DataContext绑定到我的代码中的ObservableCollection,后者在我的数据更新时更新。这些都不起作用,我没有看到任何方法来更新用户界面。

我对UWP很新,所以我不确定自己做错了什么。我知道数据绑定的概念是UWP的重要组成部分,但我不确定如何将数据绑定到此CalendarView,以便在刷新数据时刷新数据。有什么建议么?

下面是我的代码现在的快速摘录。

XAML

<CalendarView 
    Name="Calendar" 
    NumberOfWeeksInView="6" 
    CalendarViewDayItemChanging="CalendarView_DayItemChanging" 
    DataContext="{Binding CalendarDates}"> 
</CalendarView> 

代码隐藏

namespace Pages 
{ 
    public sealed partial class CalendarPage : BasePage 
    { 
     #region Private Variables 

     private CalendarPageModel PageModel = new CalendarPageModel(); 
     private ObservableCollection<DateTime> CalendarDates; 

     #endregion 

     #region Constructor 

     public CalendarPage() 
     { 
      this.InitializeComponent(); 
      CalendarDates = new ObservableCollection<DateTime>(); 
     } 

     #endregion 

     #region Events 

     private void Page_Loaded(object sender, RoutedEventArgs args) 
     { 
      SetCalendarDateRange(); //NOTE: This is done here so that my UI consistantly shows the correct dates on the screen 
      LoadData(); 
     } 

     private void CalendarView_DayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args) 
     { 
      if (!PageModel.DateHasEvent(args.Item.Date)) 
      { 
       args.Item.SetDensityColors(null); 
      } 
      else 
      { 
       List<Color> colors = new List<Color>(); 
       Color? color = Application.Current.Resources["CalendarHasEventDensityColor"] as Color?; 
       if (color != null) 
       { 
        colors.Add((Color)color); 
       } 

       args.Item.SetDensityColors(colors); 
      } 
     } 

     #endregion 

     #region Data 

     private void SetCalendarDateRange() 
     { 
      Calendar.MinDate = PageModel.StartDate; 
      Calendar.MaxDate = PageModel.EndDate; 
     } 

     private async void LoadData() 
     { 
      // get data 
      await PageModel.RefreshData(PageModel.StartDate, PageModel.EndDate); 

      // force calendar to update 
      //NOTE: This only works if the date range is actually different than what it's currently set to 
      SetCalendarDateRange(); 

      //NOTE: I have tried to just manually add a date to my observable collection to see if it'll kick off the calendar refresh, but it doesn't 
      CalendarDates.add(DateTime.Now); 
     } 

     #endregion 
    } 
} 
+0

当您更改MinDate和MaxDate但您没有完整的repro(其中'CalendarPageModel'?),因此在您的代码中无法看到问题出在哪里时,可以让日历更新UI。 'RefreshData'发生了什么?还有什么叫“LoadData”? –

+0

这些都不重要。它被抽象出来,因为我唯一的问题是如何在不更改最小/最大日期的情况下更新日历。您可以假设loadData和refreshData调用获取数据并将数据存储到CalendarPageModel类中。此时此数据未连接到CalendarView。如果您愿意,我可以删除该代码。无论如何,问题是你如何刷新CalendarView,意味着调用上面概述的导师,而不改变最小/最大日期? –

+0

对不起,Ruppe的。在手机上输入这个。 –

回答

0

坏消息
CalendarView控制不遗憾的是专为这种情况。由于它在显示大量天数时针对性能进行了优化,因此只会在加载单个日期时刷新UI。

但是......

好消息
它是可以修改的控制来创建此行为,但它需要的工作一点点。

基本原理是负责绘制密度颜色块并将它们绑定到可通过绑定更新的内容。

由于这个工作的一个例子,下面添加到页面

<Page.Resources> 
    <local:ColorBrushConverter x:Key="BrushConverter" /> 
</Page.Resources> 
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <StackPanel> 
     <CalendarView Name="Calendar" 
         DisplayMode="Month" 
         CalendarViewDayItemChanging="CalendarView_DayItemChanging" 
         > 
      <CalendarView.CalendarViewDayItemStyle> 
       <Style TargetType="CalendarViewDayItem" > 
        <Setter Property="Template"> 
         <Setter.Value> 
          <ControlTemplate TargetType="CalendarViewDayItem"> 
           <Grid Opacity="0.5"> 
            <Grid.RowDefinitions> 
             <RowDefinition Height="*"/> 
             <RowDefinition Height="*"/> 
             <RowDefinition Height="*"/> 
             <RowDefinition Height="*"/> 
             <RowDefinition Height="*"/> 
            </Grid.RowDefinitions> 
            <Rectangle Grid.Row="0" Fill="{Binding FifthColor, Converter={StaticResource BrushConverter}}" /> 
            <Rectangle Grid.Row="1" Fill="{Binding FourthColor, Converter={StaticResource BrushConverter}}" /> 
            <Rectangle Grid.Row="2" Fill="{Binding ThirdColor, Converter={StaticResource BrushConverter}}" /> 
            <Rectangle Grid.Row="3" Fill="{Binding SecondColor, Converter={StaticResource BrushConverter}}" /> 
            <Rectangle Grid.Row="4" Fill="{Binding FirstColor, Converter={StaticResource BrushConverter}}" /> 
           </Grid> 
          </ControlTemplate> 
         </Setter.Value> 
        </Setter> 
       </Style> 
      </CalendarView.CalendarViewDayItemStyle> 
     </CalendarView> 
     <Button Click="AddEventClicked">Add random event</Button> 
    </StackPanel> 
</Grid> 

和相应的代码背后:

public sealed partial class MainPage : Page 
{ 
    private MyViewModel ViewModel; 

    private DateTime today; 
    private DateTime minDate; 
    private DateTimeOffset maxDate; 

    public MainPage() 
    { 
     this.InitializeComponent(); 

     // Keep these for reference 
     this.today = DateTime.Now.Date; 
     this.minDate = new DateTime(today.Year, today.Month, 1); 
     this.maxDate = minDate.AddMonths(1); 

     // Create our viewmodel 
     ViewModel = MyViewModel.Generate(minDate.Date, maxDate.Date); 
     Calendar.MinDate = minDate; 
     Calendar.MaxDate = maxDate; 

     // Add data for the next three days - will be shown when page loads 
     ViewModel.Dates[today.AddDays(1)].Add(Colors.Red); 
     ViewModel.Dates[today.AddDays(2)].Add(Colors.Purple); 
     ViewModel.Dates[today.AddDays(2)].Add(Colors.Blue); 
     ViewModel.Dates[today.AddDays(3)].Add(Colors.Green); 
    } 

    private void CalendarView_DayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args) 
    { 
     // When the DayItem in the calendar is loaded 
     var itemDate = args?.Item?.Date.Date ?? DateTime.MinValue; 

     if (ViewModel.Dates.ContainsKey(itemDate)) 
     { 
      // Set the datacontext for our custom control 
      // - Which does support 2way binding :) 
      args.Item.DataContext = ViewModel.Dates[itemDate]; 
     } 
    } 

    private void AddEventClicked(object sender, RoutedEventArgs e) 
    { 
     var rand = new Random(); 
     var randomColor = Color.FromArgb(
             255, 
             (byte) rand.Next(0, 254), 
             (byte)rand.Next(0, 254), 
             (byte)rand.Next(0, 254)); 

     var randomDay = rand.Next(1, 29); 
     var randDateInMonth = new DateTime(today.Year, today.Month, randomDay); 

     if (ViewModel.Dates.ContainsKey(randDateInMonth)) 
     { 
      ViewModel.Dates[randDateInMonth].Add(randomColor); 
     } 
    } 
} 

public class MyViewModel 
{ 
    // The VM really just holds this dictionary 
    public Dictionary<DateTime, DensityColors> Dates { get; } 

    private MyViewModel() 
    { 
     this.Dates = new Dictionary<DateTime, DensityColors>(); 
    } 

    // Static constructor to limit the dates and populate dictionary 
    public static MyViewModel Generate(DateTime minDate, DateTime maxDate) 
    { 
     var generated = new MyViewModel(); 

     for (var i = 0; i < (maxDate - minDate).TotalDays; i++) 
     { 
      generated.Dates.Add(minDate.AddDays(i), new DensityColors()); 
     } 

     return generated; 
    } 
} 

public class DensityColors : ObservableCollection<Color>, INotifyPropertyChanged 
{ 
    // Properties that expose items in underlying OC 
    public Color FirstColor => Items.Any() ? Items.First() : Colors.Transparent; 
    public Color SecondColor => Items.Count > 1 ? Items.Skip(1).First() : Colors.Transparent; 
    public Color ThirdColor => Items.Count > 2 ? Items.Skip(2).First() : Colors.Transparent; 
    public Color FourthColor => Items.Count > 3 ? Items.Skip(3).First() : Colors.Transparent; 
    public Color FifthColor => Items.Count > 4 ? Items.Skip(4).First() : Colors.Transparent; 

    protected override void InsertItem(int index, Color item) 
    { 
     base.InsertItem(index, item); 

     // Hacky forcing of updating UI for all properties 
     OnPropertyChanged(nameof(FirstColor)); 
     OnPropertyChanged(nameof(SecondColor)); 
     OnPropertyChanged(nameof(ThirdColor)); 
     OnPropertyChanged(nameof(FourthColor)); 
     OnPropertyChanged(nameof(FifthColor)); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

public class ColorBrushConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     if (value is Color) 
     { 
      return new SolidColorBrush((Color)value); 
     } 

     return value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    { 
     throw new NotImplementedException(); 
    } 
} 

这是限制在每天(不是10 5项如内置在控制中,任何更多都被忽略),但应该给你一个如何实现你的想法或根据需要进行修改的想法。

+0

我欣赏这里的帮助马特。这看起来像一个可行的解决方案,所以将其标记为接受的答案。但是,我只是黑了一个办法来解决我的问题。基本上,我在初始页面加载时隐藏日历,然后在第一次加载我的数据之后,然后强制当前月份的日期范围,然后显示日历。从那时起,数据只会在更新日期范围时进行更新,以便CalendarViewDayItemChanging发挥作用并允许我根据该更新进行更新。有点哈克,但它的作品。 –