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
ListtoObservableCollection- NeddySpaghetti