Building ViewModels based on nested Model Entities in WPF and MVVM Pattern

后端 未结 4 1778
南方客
南方客 2021-02-05 17:22

I have a problem understanding how to build view models based on the following models

(I simplified the models to be clearer)

public class Hit
{
   publi         


        
4条回答
  •  灰色年华
    2021-02-05 17:50

    I ended up using part of the solution that Joe White suggested, in a slighty differ manner

    The solution was to just leave the models as they were at the beginning, and attaching to the collections an eventhandler for CollectionChanged of the inner collections, for example, the PatternViewModel would be:

    public class PatternViewModel : ISerializable
    {
        public Pattern Pattern { get; set; }
        public ObservableCollection Tracks { get; set; }
    
        public PatternViewModel(string name)
        {
            Pattern = new Pattern(name);
            Tracks = new ObservableCollection();
            Pattern.Tracks.CollectionChanged += new NotifyCollectionChangedEventHandler(Tracks_CollectionChanged);
        }
    
        void Tracks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (Track track in e.NewItems)
                    {
                        var position = Pattern.Tracks.IndexOf((Track) e.NewItems[0]);
                        Tracks.Insert(position,new TrackViewModel(track, this));
                    }
                    break;
                case NotifyCollectionChangedAction.Remove:
                    foreach (Track track in e.OldItems)
                        Tracks.Remove(Tracks.First(t => t.Track == track));
                    break;
                case NotifyCollectionChangedAction.Move:
                    for (int k = 0; k < e.NewItems.Count; k++)
                    {
                        var oldPosition = Tracks.IndexOf(Tracks.First(t => t.Track == e.OldItems[k]));
                        var newPosition = Pattern.Tracks.IndexOf((Track) e.NewItems[k]);
                        Tracks.Move(oldPosition, newPosition);
                    }
                    break;
            }
        }
    }
    

    So i can attach the new Color/Style/Command on the view models to keep my base models clean

    And whenever I add/remove/move items in the base models collection, the view models collections remain in sync with each other

    Luckily I don't have to manage lots of object in my application, so duplicated data and performance won't be a problem

    I don't like it too much, but it works well, and it's not a huge amount of work, just an event handler for the view model that contains others view model collections (in my case, one for PatternViewModel to sync TrackViewModels and another on TrackViewModel to manage HitViewModels)

    Still interested in your thoughs or better ideas =)

提交回复
热议问题