0

i have a List that i would like to pass to the ViewModel.Intuitively i thought it would be straightforward by passing it is a parameter to the ViewModel's constructor but on doing that i get the error that a ViewModel's constructor should be parameterless...This being the case:

public SomeMethod(){
        List<T> list = new List<T>();
        ViewModel vm = new ViewModel(list);
   }

the viewmodel:

public class ViewModel
{
    public ObservableCollection<T> Collection { get; set; }

    public ViewModel(List<T> t)
    {
        Collection = new ObservableCollection<T>();

        foreach (T item in t)
        {
              this.Collection.Add(new T (item.value));
        }
    }

what other ways can i pass the list to the ViewModel..for one i thought of creating another method in the ViewModel that accepts the list as a parameter,but how would i be able to call it from the constructor since the constructor has to pass the parameter to it too.

ch_av
  • 13
  • 4
  • You can create second parameterless constructor. – Yuri Dorokhov Feb 19 '15 at 14:22
  • you can add a parameter less constructor\ default constructor. in Visual Studio type ctor and press TAB – Shaan Feb 19 '15 at 14:23
  • @Yuri i created that already but on linking with the XAML side,it still points to the parameterless constructor and not the other one ,since it expects irt to be parameterless...something like this: – ch_av Feb 19 '15 at 14:31
  • See this post http://stackoverflow.com/questions/19747649/how-to-bind-view-to-viewmodel-with-parameters. You need to use dependency injection to pass parameters to viewmodel when binding in XAML. – Shaan Feb 19 '15 at 14:35
  • If you use MEF you can have a parameter-less constructor and DI properties instead. –  Feb 19 '15 at 14:52

1 Answers1

0

Just leave the Constructor empty and modify your Collection-Property to Property with Backing field.

After this, you can do in your setter whatever you want.

    private ObservableCollection<T> _collection
    public ObservableCollection<T> Collection { 
get{
return this._collection;
} 
set{
this._collection = value; 
// Do what you want here 
}
lokusking
  • 7,396
  • 13
  • 38
  • 57