views:

115

answers:

2

Hi,

I am trying to use MVVM light to achieve something like this. I have the following scenario:

In my Model--I have set the properties like ActivityName,Image and there is a class constructor whose is accepting 2 parameters like name and image.

Im my DataAccess--I have set the database connection and implement the required method who will fetch the data from DB and I am storing in the List and returning the list to ViewModel.

In my ViewModel--I have created the list property who will return the list by calling the GetActivities() method that I have defined in the DataAccess.

Now my problem is I am not getting how to bind it in the View so that by clicking on a button it will display the list of activities with image. By clicking on some button a new window should open with the desired result. How to bind the above list and implement the button functionality using MVVM light.

Kindly help?

Thanks

A: 

Bind to DataContext of the control

Ragunathan
+1  A: 
  • First of all, use an ObservableCollection instead of a List as it would notify the view when property or collection changes.
  • Then set the DataContext of your view to the viewmodel. If you use MVVMLight View Class, then the DataContext would be automatically set. You've to just give the ViewModel Name there.
  • Then set the ItemsSource of the DataGrid like this <dg:DataGrid ItemsSource="{Binding YourListInViewModel}"/>
  • For handling click event you can use the Event-To-Command behaviour and write your logics in the Button's corresponding Command handler.
Veer
You mean to say I have to use ObservableCollection in both the Data Aceess while storing and in View Model while returning? Kindly suggest?
Tarun
You need to create an ObservableCollection in the VM. If GetActivities() returns a list then create an OC out of it like this `ObservableCollection a = new ObservableCollection(GetActivities());`. But I would recommend you to create a method `GetActivities()` that would return an `IEnumerable` rather, since it would avoid copying twice: one from database to a list and then to OC.
Veer
Thanks. I will try it out and let u know
Tarun