6

I'm struggling to find a solution to the problem of having to maintain two lists.

I'm using MVVM, but don't want my model to use ObservableCollection. I feel this is best to encapsulate and allows me to use different views/patterns (a console for example). Instead of setting up my structure like this:

public class MainWindow {
  // handled in XAML file, no code in the .cs file
}

public abstract class ViewModelBase : INotifyPropertyChanged {
  // handles typical functions of a viewmodel base class
}

public class MainWindowViewModel : ViewModelBaseClass {
  public ObservableCollection<Account> accounts { get; private set; }
}

public class Administrator {
  public List<Account> accounts { get; set; }

  public void AddAccount(string username, string password) {
    // blah blah
  }
}

I would like to avoid having two different collections/lists in the case above. I want only the model to handle the data, and the ViewModel to responsible for the logic of how its rendered.

2
  • it sounds like you'll need to have events on your Administrator class for delete/add/edit and have your MainWindowViewModel observe those changes. Commented Nov 12, 2014 at 0:59
  • Right and that's how it's implemented, but not I need to be able to bind to the list in Administrator and have it update when things are added, removed, or edited. Commented Nov 12, 2014 at 1:19

1 Answer 1

8

what you could do is to use a ICollectionView in your Viewmodel to show your Model Data.

public class MainWindowViewModel : ViewModelBaseClass {
 public ICollectionView accounts { get; private set; }
 private Administrator _admin;

  //ctor
  public MainWindowViewModel()
  {
     _admin = new Administrator();
     this.accounts  = CollectionViewSource.GetDefaultView(this._admin.accounts);
  }

  //subscribe to your model changes and call Refresh
  this.accounts.Refresh();

xaml

  <ListBox ItemsSource="{Binding accounts}" />
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for use of CollectionViewSource. Do note that the common naming standard uses PascalCasing for properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.