Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection in ViewModel, List in Model

Tags:

c#

wpf

xaml

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.

like image 455
keelerjr12 Avatar asked Nov 12 '14 00:11

keelerjr12


People also ask

Can a ViewModel have multiple models?

ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method. In the above example, we have the required View model with two properties.

Can ViewModel have reference view?

Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

What should be in a ViewModel?

The simplest kind of viewmodel to understand is one that directly represents a control or a screen in a 1:1 relationship, as in "screen XYZ has a textbox, a listbox, and three buttons, so the viewmodel needs a string, a collection, and three commands." Another kind of object that fits in the viewmodel layer is a ...


1 Answers

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}" />
like image 99
blindmeis Avatar answered Oct 01 '22 07:10

blindmeis