Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind an ObservableCollection to a ListView

I am having an immense amount of trouble getting my data to bind correctly. I have read most the posts on here from people with similar issues, but for some reason I just can't get it to click.

The XML for my table is:

<Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}" >
...
<ListView Height="124" HorizontalAlignment="Left" Margin="12,46,0,0" Name="listViewDocuments" VerticalAlignment="Top" Width="Auto" DataContext="{Binding DocumentList}">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="160" Header="Description" DisplayMemberBinding="{Binding Description}"/>
            <GridViewColumn Width="160" Header="Date Filed" DisplayMemberBinding="{Binding DateFiled}"/>
            <GridViewColumn Width="160" Header="Filed By" DisplayMemberBinding="{Binding UserFiledName}"/>
            <GridViewColumn Width="150" Header="Page" DisplayMemberBinding="{Binding Pages}"/>
            <GridViewColumn Width="150" Header="Notes" DisplayMemberBinding="{Binding Notes}"/>
            <GridViewColumn Width="Auto" Header="" />
        </GridView>
    </ListView.View>
</ListView>

Within my code I have:

public ObservableCollection<Document> _DocumentList = new ObservableCollection<Document>();

...

public ObservableCollection<Document> DocumentList{ get { return _DocumentList; } }

...

public class Document
{
    public string Description { get; set; }
    public string DateFiled { get; set; }
    public string UserFiledName { get; set; }
    public string Pages { get; set; }
    public string Notes { get; set; }
    public string Tag { get; set; }

}

In an attempt to update the table I use:

_DocumentList.Add(new Document
{
    Description = dr["Description"].ToString(),
    DateFiled = dr.GetDateTime(dr.GetOrdinal("DateFiled")).ToShortDateString(),
    UserFiledName = dr["UserFiledName"].ToString(),
    Pages = dr.GetInt32(dr.GetOrdinal("Pages")).ToString(),
    Notes = dr["Notes"].ToString(),
    Tag = dr["FileID"].ToString()
});

New items seem to be getting added correctly, but nothing is updated on the listView.

I have read through tutorials like this: http://www.switchonthecode.com/tutorials/wpf-tutorial-using-the-listview-part-1

And I have tried adding all of the notification code that is suggested in other posts. Nothing is working for me.

And ideas would be appreciated.

like image 686
Nathan Tornquist Avatar asked May 18 '12 20:05

Nathan Tornquist


1 Answers

Instead of DataContext="{Binding DocumentList}" try ItemsSource="{Binding DocumentList}".

like image 185
Bryan Walker Avatar answered Oct 13 '22 20:10

Bryan Walker