I've read some questions on stackoverflow targeting this issue but found none actually providing a way on how to do it properly. I just don't feel right about my implementation.
Given the following situation: I got a list of playlists (music playlists, for example) that do contain tracks.
class PlaylistModel
-> string Name // Name of the playlist
-> List<TrackModel> Tracks // tracks contained by the playlist
class TrackModel
-> string Name
Given this scheme, how would I map this relation if my ViewModel shows playlists and the associated tracks as a TreeView that may change during user interaction?
I already thought about the relationship and ended up using something like this:
public class PlaylistViewModel : ViewModelBase
{
private PlaylistModel _Playlist;
public PlaylistModel Playlist
{
get { return _Playlist; }
set
{
if (_Playlist == value) return;
_Playlist = value;
NotifyOfPropertyChange(() => Playlist);
}
}
public ObservableCollection<TrackViewModel> Tracks
{
get { return new ObservableCollection<TrackViewModel>(Playlist.Tracks.Select(track => new TrackViewModel(track))); }
set
{
var tracksCollection = new ObservableCollection<TrackViewModel>(Playlist.Tracks.Select(track => new TrackViewModel(track)));
if (tracksCollection == value) return;
Playlist.Tracks = new List<TrackModel>(value.Select(trackViewModel => trackViewModel.Track));
NotifyOfPropertyChange(() => Tracks);
}
}
public string Name
{
get { return Playlist.Name; }
set
{
if (Playlist.Name == value) return;
Playlist.Name = value;
NotifyOfPropertyChange(() => Name);
}
}
}
(just included the essential code part)
You might have noticed the casting around the _Playlist.Tracks
property which is of type TrackModel
. That's the issue here. I just could have implemented INotifyPropertyChanged in the TrackModel
class but I also don't feel right about this one since it simply isn't my UI interaction layer.