开发者

How to change an item in a databound ListView from another class?

开发者 https://www.devze.com 2023-01-08 02:18 出处:网络
I have a ListView set up to view a number of records from a database, and therefore it is bound to an ObservableCollection of SongData:

I have a ListView set up to view a number of records from a database, and therefore it is bound to an ObservableCollection of SongData:

public class SongData {
    Id { get; set; }
    Title { get; set; }
    Artist { get; set; }
}

Now, I have an EventHandler set up with an EventSetter in order to display a new Window with some sort of edit form when the user doubleclicks on one of the ListViewItems. When the user changes the data in the new window, it is saved to the database.

I'm trying to figure out a way to change the data in the ListView. I've encountered a few problems. First of all, since the ObservableCollection is a private property, so I can't acces it from another class/window. I can think of a few ways to get this part to work, but they're not very elegant. Any suggestions?

Secondly, I have no idea how I can get the correct SongData 开发者_如何转开发object from the ObservableCollection, as I only have the Id available to look it up. I have tried to pass the entire SongData object instead of just the Id, but that didn't seem to be working. I think there should be a simple anwser to this question, but I can't find it...

The main question is how I can change an item from a ListView databound to an ObservableCollection<SongData> from another class, when I only have the Id of the SongData object available.


Eventhough this is do-able in the usual way, you can consider implementing the ViewModel pattern so that you would have a ViewModel for each Window.

Basically you need to bind the ListView's SelectedItem to a property that implements INotifyPropertyChanged.

In order this to be available to other classes you can register for PropertyChanged messages in those classes.

Hence whenever you select an item, the property bound to it will also change accordingly which would eventually broadcast the PropertyChanged message which would be captured by those classes which have registered for it.

Side Note: Shall your properties be public

0

精彩评论

暂无评论...
验证码 换一张
取 消