Update listview items when datasource changes
I have a list that I use as a log. I want to see the log in a listview therefor I have created:
<ListView Margin="12,114,12,12" Name="listView1" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" />
The log gets populated with a field on a class that I did not create, so there is a class as:
SomeClass
{
public ReadOnlyCollection<Status> Log
{
get
{
return _log.AsReadOnly();
}
}
// other method and fields
// etc...
}
so I am able to see the list items. Moreover, I am able to populate the listview with this log as:
listView1.DataContext = server.Log; // server is an instance of SomeClass
the only problem is that every time the log changes the listview does not update. I have to call listView1.DataContext = server.Log; every time I wish to refresh开发者_Go百科 the log.
how can I avoid having to refresh the listview?
You need to use an ObservableCollection<Status>
instead of a ReadOnlyCollection<Status>
The reason for this is that Observable collection notifies the controls it is bound to whenever an item is added/removed.
If you want each Status
object to notify the view when one of their property changes (so a property in a Status
instance changes, but there is no add/remove on the collection), then Status
has to implement INotifyPropertyChanged
, and each Property needs to raise the PropertyChanged
event on its setter.
You can do all this via composition also, if it's a third-party dll.
Sidenote: why do you have a Margin
above 100? you should use ContentPresenters such as Grid
or StackPanels
精彩评论