ListBox does not get updated WPF

134 Views Asked by At

The wrapper class:

public class Multimedia : INotifyPropertyChanged
{
   //... constructor
   //... empty constructor
   //... getters and setters for properties
   public event PropertyChangedEventHandler PropertyChanged;

   public void OnPropertyChanged(string name)
   {
       PropertyChangedEventHandler handler = PropertyChanged;
       if (handler != null)
       {
           handler(this, new PropertyChangedEventArgs(name));
       }
   }
}

The collection:

public class MultiMediaList : ObservableCollection<Multimedia>
{
        Multimedia mediaWrapper = new Multimedia();

        //... constructor with creating several default objects of Multimedia

        public void addMedia(string title, string artist, string genre, MediaType type)
        {
            this.Add(new Multimedia(title, artist, genre, type));
            mediaWrapper.OnPropertyChanged("MultiMediaList");
        }
}

This is how I bind the ListBox to the ObservableCollection: Code-behind:

public partial class MainWindow : Window
{
        MultiMediaList mediaList;
        public MainWindow()
        {
            InitializeComponent();
            mediaList = new MultiMediaList();
            LB_media.ItemsSource = mediaList;
        }
}

XAML:

<ListBox Name="LB_media" DisplayMemberPath="Title" ... />

Nevertheless, when I add a new entry in the Collection, the ListBox does not get updated. I tried debugging, to see whether at least the new entry is being added to the Collection - it is.

It all looks correct to me, from research that I did and tryouts. Any ideas where am I missing something or doing something wrong?

1

There are 1 best solutions below

0
Paul Abbott On BEST ANSWER

If all you're trying to do is add to the list, you don't need any wrapper classes or any events because ObservableCollection already implements INotifyCollectionChanged.

public class MultiMediaList : ObservableCollection<Multimedia>
{
    //... constructor with creating several default objects of Multimedia

    public void addMedia(string title, string artist, string genre, MediaType type)
    {
        this.Add(new Multimedia(title, artist, genre, type));
    }
}

That's it. Keep your MainWindow as-is. If you add a button to the form,

private void Button_Click(object sender, RoutedEventArgs e)
{
    mediaList.addMedia("ccc", "ccc", "ccc", MediaType.Whatever);
}

will cause the new item will automatically show up.