2017-02-07 72 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發揮作用並允許我根據該更新進行更新。有點哈克,但它的作品。 –