SYNTAX HIGHLIGHTER

Monday, March 11, 2013

WPF DataGrid Row Select with MVVM


Introduction

In this article I am going to discuss how to select Row in the DataGrid control with MVVM pattern. Basically, MVVM pattern directly engage with WPF/Silverlight using Command binding. Command binding is a power full feature in the WPF/Silverlight. you can find new version of this here

Prerequisites
In this sample, I am using Visual studio 2010 and .net framework 4.0

Solution
1.      1.  I am creating a WPF project Called “SolutionFileManager” and Add  3 folders called “Models,              ViewModels and Views” 


2         2.  Add new class called “DataFile” into Models .  This is our Domain Entity and that contains few properties

            3.       Add new “ViewModel “ called “DataFileListViewModel”.  DataFileListViewModel responsible for handing Command which are fired in the views and make data for the relevant view

       4.        Add new class for ICommand Implementation called “DelegateCommand”
          
5.      Add NuGet package Reference
a.       Right click on project and select “Manage NuGet Packages…”
b.      Type “expression blend” in the search box
c.       Select “Blend Interactivity for WPF v4.0” and click install


              d.  Nuget package manager add Reference for “Microsoft.Expression.Interactions and System.Windows.Interactivity”

     6.     Add new userControl for Views folder called “DataFileList.xaml” and set it as startup window
      
             
             7.   Add Xaml markup for DataFileList.xaml. Below  Xaml add “PreviewMouseUP” event triger using interactivity


      8.    Add Viewmodel binding to code behind  file

        9.   Run the application and click on grid Row

              Download code sample Click here

4 comments:

  1. How to select checkbox in datagrid cell?

    ReplyDelete
  2. This is *not* what Blend.Interactivity.Wpf is for, you're basically destroying the separation of concerns between View and ViewModel while also avoiding using binding points that exist already for this task.

    You can use a CollectionView with IsSynchronizedWithCurrentItem=True on the DataGrid, then use the CollectionView's "CurrentItem" property in the ViewModel, or you can bind the DataGrid's "SelectedItem" property to a property in the ViewModel and provide INotifyPropertyChanged if you need to perform actions upon this changing other than binding. If you only require binding, you need to just bind the other bits in the view to the object in the ViewModel, decoupling everything nicely.

    ReplyDelete
  3. I appreciate your comments ("Yushatak") and agree with you I will repost this with prism 5

    ReplyDelete