0
votes

I have a class YouTubeVideo which contains some variables, which I would like to show on the UI. Therefore I created a custom control which shows all the data of the class. There are more than one instances of the class, so I would like to use an ItemsControl to show them on the screen like in a StackPanel. I defined a ViewModel for the ItemsControl and I'm adding the custom usercontrols from my window code behind to the ViewModel, however the ItemsControl stays empty.

ViewModel

public class VideoInfoListModel : INotifyPropertyChanged
{
    private List<VideoInfoListItem> _loadedVideos = new List<VideoInfoListItem>();

    public List<VideoInfoListItem> LoadedVideos
    {
        set { 
            _loadedVideos = value;
            NotifyPropertyChanged("LoadedVideos");
        }

        get { return _loadedVideos; }
    }

    public void AddVideo(YouTubeVideo video)
    {
        LoadedVideos.Add(new VideoInfoListItem(video));
        NotifyPropertyChanged("LoadedVideos");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}  

The ItemsSource XAML

    <ItemsControl ItemsSource="{Binding LoadedVideos, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  x:Name="videoInfoList" Margin="0">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>  

From the window code behind I set the datacontext for the ItemsControl to the ViewModel in the constructor:
InitializeComponent(); videoInfoList.DataContext = new VideoInfoListModel();

I debugged the ViewModel and I can see that my usercontrols are being added to the collection successfully, the PropertyChanged does also fire.
Thanks

1
Try changing List to ObservableCollection - NeddySpaghetti
@NedStoyanov please add it as an answer, as you where first. Thank both off you! Spend way to much time in this.. - Kimmax

1 Answers

1
votes

In order to observe changes in a collection WPF provides the ObservableCollection class which implements INotifyCollectionChanged and INotifyPropertyChanged. Replace List<T> with ObservableCollection<T> and your code should work.