Reputation: 1
I am having some trouble to bind my collection to my listview. I have tried a lot of different approaches from others on here for binding, and also followed this tutorial at first. I made it to work but it was not the way I wanted.
Anymway, here is the XML:
<ListView Grid.Row="0" ItemsSource="{Binding SongList}" SelectionMode="Extended" x:Name="ListViewMain" VerticalAlignment="Top" ScrollViewer.VerticalScrollBarVisibility="Visible" Margin="0,1,0,0" Height="264" >
<ListView.View>
<GridView>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" Width="500"/>
<GridViewColumn Header="Artist" DisplayMemberBinding="{Binding Artist}" Width="100"/>
<GridViewColumn Header="Album" DisplayMemberBinding="{Binding Album}" Width="100"/>
<GridViewColumn Header="Length" DisplayMemberBinding="{Binding Length}" Width="100"/>
<GridViewColumn Header="Location" DisplayMemberBinding="{Binding Songfile}" Width="100"/>
</GridView>
</ListView.View>
</ListView>
In my code, to add items to my collection, I do :
public MainWindow()
{
InitializeComponent();
...
PlayListItem addsong = new PlayListItem(title, artist, album, length, filename);
}
The PlayListItem class with the ObservableCollection :
public class PlayListItem
{
public ObservableCollection<Song> _SongList = new ObservableCollection<Song>();
public ObservableCollection<Song> SongList { get { return _SongList; } }
public PlayListItem(string _Title, string _Artist, string _Album, string _Length, string _Filename)
{
_SongList.Add(new Song
{
Title = _Title,
Artist = _Artist,
Album = _Album,
Length = _Length,
SongFile = _Filename,
});
}
public class Song
{
public string Artist { get; set; }
public string Album { get; set; }
public String Title { get; set; }
public string Length { get; set; }
public String SongFile { get; set; }
}
}
I think my items are added correctly each time I call the constructor, but it does not get updated on the ListView. I do not have some errors about the binding in the Output window either.
Any ideas and help would be appreciated.
EDIT :
By adding :
ListViewMain.ItemsSource = addsong.SongList;
Right after creating a new PlayListItem seems to solve the problem, as the ListView is now printing the item.
Upvotes: 0
Views: 2327
Reputation: 8696
Two problems. 1) I don't see where a DataContext is set. You can do that at the window level or individual control level. 2). PlayListItem does not implement INotifyPropertyChanged. If you set SongList after InitializeComponent, INotifyPropertyChanged is needed, but not if it's before.
Upvotes: 1
Reputation: 500
Did you try using a two-way binding? A one way binding will not update the other side. Add this: Mode="TwoWay"
in the itemsource binding.
Upvotes: 0