Search code examples
c#wpfxamlpropertychanged

Why ItemsControl does not refreshed


I have the following xaml:

<Window.DataContext>
    <local:CalendarViewModel />
</Window.DataContext>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition
            Width="55*" />
        <ColumnDefinition
            Width="27*" />
    </Grid.ColumnDefinitions>
    <local:UserControlCalendar
        x:Name="ControlCalendar"
        Grid.Column="0">
    </local:UserControlCalendar>
    <ItemsControl
        x:Name="HistoryControl"
        Grid.Column="1"
        Width="210"
        Margin="30,10,0,0"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        ItemTemplate="{StaticResource DataTemplate.HistoryItems}"
        ItemsPanel="{StaticResource ItemsPanel.Vertical}"
        ItemsSource="{Binding ListHistoryItems, Mode=OneWay}">
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Setter Property="FrameworkElement.Margin" Value="0,10,0,0" />
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
</Grid>

When select a date in UserControlCalendar should change the contents of the "HistoryControl". In ViewModel Property ListHistoryItems changed, but ItemsControl in UserControl don't refreshed. This is ViewModel:

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace CustomCalendar
{
  public class CalendarViewModel :  INotifyPropertyChanged
  {
    private ObservableCollection<HistoryItems> _listHistoryItems;
    private DateTime _selectedDate;

    public CalendarViewModel()
    {
    }

    public DateTime SelectedDate
    {
        get { return _selectedDate; }
        set
        {
            _selectedDate = value;
            if (_selectedDate != null)
            {
                ListHistoryItems = new ObservableCollection<HistoryItems>(GetHistoryItems(_selectedDate));
            }
        }
    }

    public ObservableCollection<HistoryItems> ListHistoryItems
    {
        get { return _listHistoryItems; }
        set
        {
            _listHistoryItems = value;
            RaisePropertyChanged("ListHistoryItems");
        }
    }

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
  }
}

The problem is that Event PropertyChanged are always null. Why? Thanks in advance for your help.


Solution

  • I found my mistake. To transfer SelectedDate of the UserControlCalendar in the MainWindow, I have created in UserControlCalendar new ViewModel. Therefore, nothing worked. Now I removed that object, and all works fine. Now there's another question, how to transfer the SelectedDate in the ViewModel. I think the use of Prism and EventAggregator.