Sunday, April 12, 2015

MVVM Part 6

Binding a DataGrid

Let's add a new requirement. We also need to display a list of employees in a data grid. Now some of you are probably thinking that I am very skilled at creating badly designed screens but I've learned from the absolute masters of bad screen design - my business analysis team.

    1. We will start by adding a new table to our database with the following SQL script.
USE [MVVM_Walkthrough]
GO

CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
[EmployeeID] ASC
) ON [PRIMARY]

    2. Let's add a row to the table
INSERT INTO Employee VALUES ('Billy', 'Bee')

    3. In the solution explorer double-click on the MVVM_Walkthrough_Model.edmx
    4. In the edmx client area right-click and select "Update Model from Database"
    5. Check the Employee table and click [Finish]
    6. Now we have updated our Model we need to update the ViewModel. Add the following code to the constructor.
     Dim emp = (From a In Model.Employees Select a).ToList()
  Me.Employees = New ObservableCollection(Of Employee)(emp)

     7. Now we need a private member and a public property like this...
    Private _Employees As ObservableCollection(Of Employee)
    Public Property Employees As ObservableCollection(Of Employee)
        Get
            Return _Employees
        End Get
        Set(value As ObservableCollection(Of Employee))
            If Not value.Equals(_Employees) Then
                _Employees = value
                NotifyPropertyChanged("Employees")
            End If
        End Set
    End Property

    8. Build the application. Now we can update the view. Add another RowDefinition (there are now four) and make the height of the third row Height="200". Move the button down to Grid.Row="3".
    9. Add a DataGrid like this...
   <DataGrid Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Employees}" AutoGenerateColumns="False" IsReadOnly="True">
       <DataGrid.Columns>
           <DataGridTextColumn Header="ID" Binding="{Binding Path=EmployeeID}"/>
           <DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}"></DataGridTextColumn>
           <DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}"></DataGridTextColumn>
       </DataGrid.Columns>
   </DataGrid>

Nothing surprising here. If we run the application now we can see Billy Bee in the data grid.


In the next blog entry we will discover what it would take to make the data grid editable.

No comments:

Post a Comment