Silverlight / WPF - reg binding values in data grid.

Asked By Ramachandran on 20-Nov-11 09:01 AM
Hi ,
        I am having two xaml files  one is parent file and another one is child file i am calling that child xaml in parent xaml's button event and i want to bind a collection list throught xaml1 to xaml2. that collections has to bind in the Data Grid's Items source of Xaml 2 in MVVM Pattern using C# silverlight  plse help me....
Suchit shah replied to Ramachandran on 20-Nov-11 09:43 AM

Add a Models folder to your Silverlight project. In that folder, add a Student class.

In C#:

using System;

namespace InStepSM.SL.Models 

    public class Student 
    { 
      public String StudentName { get; set; } 
      public int StudentId { get; set; } 
      public decimal Project1Score { get; set; } 
      public decimal Project2Score { get; set; } 
      public decimal Project3Score { get; set; } 
    } 
}

This class includes a student's name, Id, and three scores.

Step 2 requires building a new class that is the View/Model.

Add a ViewModels folder to your Silverlight project. In that folder, add a StudentViewModel class.

Implement INotifyPropertyChanged in the ViewModel class. That ensures that the UI is notified when properties of the View/Model are changed.

NOTE: INotifyPropertyChanged requires the System.ComponentModelnamespace.

Add a property that contains the list of students. The View will bind to this property. You can define the property to be a List, but if you instead use an ObservableCollection, changes to the list will be reflected in the user interface.

NOTE: ObservableCollection requires the System.Collections.ObjectModelnamespace.

In C#:

using System.Collections.ObjectModel; 
using System.ComponentModel; 
using InStepSM.SL.Models;

namespace InStepSM.SL.ViewModels 

    public class StudentViewModel: INotifyPropertyChanged 
    { 
      public event PropertyChangedEventHandler PropertyChanged;

      private ObservableCollection<Student> _studentList; 
      public ObservableCollection<Student> StudentList 
      { 
        get 
        { 
          return _studentList; 
        } 
        set 
        { 
          if (_studentList != value) 
          { 
            _studentList = value; 
            OnPropertyChanged("StudentList"); 
          } 
        } 
      }

      public StudentViewModel() 
      { 
        PopulateStudents(); 
      }

      private void OnPropertyChanged(string propertyName) 
      { 
        if (PropertyChanged != null)     
          PropertyChanged(this, 
            new PropertyChangedEventArgs(propertyName)); 
      }

      public void PopulateStudents() 
      { 
        var itemList = new ObservableCollection<Student>() 
            {new Student(){StudentName="Frodo Baggins", 
                    Project1Score = 89M, 
                    Project2Score=93M, 
                    Project3Score=88M}, 
            new Student(){StudentName="Rosie Cotton", 
                    Project1Score = 97M, 
                    Project2Score=93M, 
                    Project3Score=94M}, 
            new Student(){StudentName="Samwise Gamgee", 
                    Project1Score = 83M, 
                    Project2Score=90M, 
                    Project3Score=85M}, 
            new Student(){StudentName="Peregrin Took", 
                    Project1Score = 69M, 
                    Project2Score=72M, 
                    Project3Score=75M}}; 
        StudentList = itemList; 
      }

    } 

Step 3 hooks the View to the View/Model. There are several choices for hooking them together.

  • Option 1: Use the code behind. 

using System.Windows.Controls; 
using System.Windows.Navigation; 
using InStepSM.SL.ViewModels;

namespace InStepSM.SL.Views 

    public partial class Overview : Page 
    { 
      public StudentViewModel vm { get; set; }

      public Overview() 
      { 
        InitializeComponent(); 
        vm = new StudentViewModel(); 
        this.DataContext = vm; 
      }

      private void dataGrid1_SelectionChanged(object sender, 
                  SelectionChangedEventArgs e) 
      { 
        vm.SomeMethod(); 
      }

    } 

And the xaml for the DataGrid would look something like this:

<sdk:DataGrid AutoGenerateColumns="true" 
    ItemsSource="{Binding StudentList}" 
    Height="200" 
    Name="dataGrid1" 
    Width="500" 
    SelectionChanged="dataGrid1_SelectionChanged" />

Where sdk is:

xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk


  • Option 2: Define the instance of the View/Model in the xaml. 

using System.Windows.Controls; 
using System.Windows.Navigation;

namespace InStepSM.SL.Views 

    public partial class Overview : Page 
    { 
      public Overview() 
      { 
        InitializeComponent(); 
      } 
    } 
}

The xaml contains the reference to the View/Model, shown in Red:

<navigation:Page x:Class="InStepSM.SL.Views.Overview"    

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
xmlns:x="
http://schemas.microsoft.com/winfx/2006/xaml"  
xmlns:d="
http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d" 
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly= 
                  System.Windows.Controls.Navigation" 
xmlns:vms ="clr-namespace:InStepSM.SL.ViewModels" 
xmlns:sdk="
http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
d:DesignWidth="640" d:DesignHeight="480" 
Title="Overview Page" >

    <!-- Reference the View/Model --> 
    <navigation:Page.DataContext> 
      <vms:StudentViewModel/> 
    </navigation:Page.DataContext>

...

</navigation:Page>

The above vms namespace line references the namespace for our View/Model. The DataContext lines set the DataContext of the page to the StudentViewModel. When the designer executes this xaml, it creates an instance of the StudentViewModel class, which in turn executes the constructor. So any code in the View/Model's constructor is executed by the designer.

Step  binds the property in the View/Model to the DataGrid in the xaml.

<sdk:DataGrid AutoGenerateColumns="true" 
    ItemsSource="{Binding StudentList}" 
    Height="200" 
    Name="dataGrid1" 
    Width="500" />

 The grid data now appears in the designer:

image

And the resulting application appears as follows:

image

This post provides the very basics of using MVVM in a Silverlight application.