Introduction

This sample is just to demonstrate the basic concepts and wiring involved in a simple master/detail scenario, where you want to show an edit form for the currently selected item in a DataGrid.

 

Building the Sample

Just download, unzip, open and run!

 

Description

This sample shows how little code is needed to build a user interface, and bind to a collection of data.

In this example, the data is created as a collection in code and the DataContext of the page is itself, which exposes the property to direct binding, for the DataGrid ItemsSource.

C#
Edit|Remove
    MyCollection = new List<Person> 
    { 
        new Person { FirstName = "Fred", LastName="Smith" }, 
        new Person { FirstName = "Tom", LastName="Jones" } 
    }; 
    DataContext = this;
In this sample, the Person class inherits from DependencyObject and exposes DependencyProperties, but it could just as easily implement INotifyPropertyChanged.
The DataGrid binds two custom DataGridTextColumns to the class to display the data.
 
C#
Edit|Remove
    <DataGrid x:Name="dataGrid" HorizontalAlignment="Center" VerticalAlignment="Center" ItemsSource="{Binding MyCollection}" AutoGenerateColumns="False"> 
        <DataGrid.Columns> 
            <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/> 
            <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/> 
        </DataGrid.Columns> 
    </DataGrid>
 
You can actually click again on the DataGrid cell and enter editing mode, and chaneg the values directly, but you may often prefer more control, with your own details form.
The details form, has it's DataContext bound to the SelectedItem of the DataGrid. The Selected item is the specific Person Class that we want to edit.
XAML
Edit|Remove
    <Grid Margin="10" DataContext="{Binding SelectedItem, ElementName=dataGrid}" >
 
The details form uses TextBoxes, which by default are two-way. We have also added UpdateSourceTrigger=PropertyChanged, so changes are instantly reflected back in the DataGrid.
XAML
Edit|Remove
    <TextBox Grid.Column="1" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" MinWidth="100"/> 
    <TextBox Grid.Column="1" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Grid.Row="1" MinWidth="100"/> 
 

 

Source Code Files

 

This project was created as demonstration to answer to a forum question.