运行时期间的ObservableCollection数据绑定

时间:2014-10-31 09:35:04

标签: c# wpf data-binding calendar observablecollection

我有一个小问题。我正在制作一个包含一些列表框元素的日历应用程序。每个日历视图都会从TKey = DateTimeTValue = ObservableCollection <CalendarEvent>的字典中检索它的“日历事件”。现在,这适用于已有预定义事件的任何日历日。我可以将数据绑定到一个属性,该属性包含对该特定日历日的字典条目的引用。但是,我的应用程序的另一个功能应该是在运行时添加事件的能力。我现在所做的是,如果该特定日历日没有字典键,它只是将Events属性设置为null,然后我在运行时更改它,如果当天添加了一个事件,不幸的是它似乎没有喜欢这样,它没有正确地“绑定”,或者说。

这是代码

    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 个答案:

答案 0 :(得分:1)

我没有看到你在任何地方举起PropertyChanged事件来通知绑定更改的视图。您应该在INotifyPropertyChanged模型上实现CalendarDayView,并在您的属性设置器中引发已实现的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));
    }
}
相关问题