运行时ObservableCollection数据绑定

本文关键字:数据绑定 ObservableCollection 运行时 | 更新日期: 2023-09-27 18:28:30

我有一个小问题。我正在制作一个带有一些列表框元素的日历应用程序。每个日历视图从字典中检索其"日历事件",其中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>

运行时ObservableCollection数据绑定

我没有看到您在任何地方引发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));
    }
}