2014-10-31 57 views
0

我遇到一個小問題。我正在製作一些帶有一些列表框元素的日曆應用程序。每個日曆視圖從字典中檢索它的「日曆事件」,其中TKey = DateTimeTValue = ObservableCollection <CalendarEvent>。現在,對於任何已有預定義事件的日曆日,此工作正常。我可以將數據綁定到一個屬性,該屬性包含對特定日曆日的字典條目的引用。然而,我的應用程序的另一個功能應該是在運行時添加事件的功能。我現在所做的是,如果在特定的日曆日沒有字典鍵,它只是將Events屬性設置爲null,然後在運行時如果在那一天添加了事件,則更改它,不幸的是它看起來不像像這樣,它不會「束縛」,或者說這樣說。運行時ObservableCollection數據綁定

下面是代碼

public CalendarDayView(DateTime date) 
    { 
     DataContext = this; 
     Date = date; 
     Events = CalendarRepository.Instance.Entries.ContainsKey(date) ? CalendarRepository.Instance.Entries[date] : null; 
    } 

    public DateTime Date { get; set; } 
    public ObservableCollection<CalendarEvent> Events { get; set; } 
    /// <summary> 
    /// This method will set the listbox item source to the ObservableCollection if it hasn't been set already 
    /// </summary> 
    public void UpdateItemSource() 
    { 
     if (Events == null) 
      // This is the part that doesn't do anything unfortunately 
      Events = CalendarRepository.Instance.Entries[Date]; 
    } 

XAML標記

<ControlTemplate TargetType="{x:Type local:CalendarDayView}"> 
        <Border BorderBrush="Gray" BorderThickness="0.2" Width="100" Height="100"> 
         <Grid Name="contentGrid"> 
          <ListBox 
           Name="entriesListBox" Background="LightYellow" FontSize="10" 
            ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
           ItemsSource="{Binding Events}"> 
          </ListBox> 
         <!-- Date display below --> 
          <TextBlock 
           Name="dateTextBlock" Text="{Binding Date, StringFormat={}{0:dd-MMM}, UpdateSourceTrigger=PropertyChanged}" 
           FontFamily="Segoe UI Light" FontSize="18" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="5"/> 
         </Grid> 
        </Border> 
       </ControlTemplate> 

回答

1

我沒有看到你提高PropertyChanged事件的任何地方以通知的結合改變了看法。您應該在CalendarDayView模型上執行INotifyPropertyChanged,並在用作綁定源的屬性設置器中提升實施的PropertyChanged事件(本例中爲Events)。

以下代碼顯示了一個簡單的示例,但將PropertyChanged功能添加到基礎模型類可能會更好。

public class CalendarDayView : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private ObservableCollection<CalendarEvent> _events; 

    public ObservableCollection<CalendarEvent> Events 
    { 
     get { return _events; } 
     set 
     { 
      _events = value; 
      RaisePropertyChanged("Events"); 
     } 
    } 

    protected void RaisePropertyChanged(string propertyName) 
    { 
     var handler = PropertyChanged; 
     if (handler != null) 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
+0

謝謝,這正是我一直在尋找的! – 2014-10-31 10:25:29

相關問題