简体   繁体   中英

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.

而不是DataContext="{Binding DocumentList}"尝试ItemsSource="{Binding DocumentList}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM