Wednesday, September 26, 2012

WCF Service Returns List of Objects to WPF DataGrid

Today we will build WCF service that returns a list of objects, an Employee objects, in our case. And we will build a WPF client application which will show the result in DataGrid.

First, let's create WCF service. Choose WCF Service Application from the list:
Add new project (WCF Service)
Visual Studio will automatically create template project with IService.cs and Service.svc files, where actually all the service logic will be written. I added the Employee class and edited Service.cs and IService.cs in order to service be able to return a list of employees. Let's see:

public class Employee
    public Employee(string name, string email, string position, int age)
        Name = name;
        Email = email;
        Position = position;
        Age = age;            
    public string Name { get; set; }
    public string Email { get; set; }
    public string Position { get; set; }
    public int Age { get; set; }
We must state DataContract attribute on our Employee class because we are going to send employee objects to the client.

public interface IService
    List<Employee> GetEmployees();     
public class Service : IService
    public List<Employee> GetEmployees()
        List<Employee> employees = new List<Employee>();
        employees.Add(new Employee("John", "", "Developer", 32));
        employees.Add(new Employee("Smith", "", "Service", 45));
        employees.Add(new Employee("Lucas", "", "Manager", 25));
        employees.Add(new Employee("Richard", "", "IT", 31));
        employees.Add(new Employee("Anna", "", "HR", 28));
        return employees;
Ok, the service is ready to send employee list to the client. Now let's create our WPF client that will connect to the service and retrieve the data. Add new WPF project to the solution:

Add New Project - WPF Client

Now we need to add reference to our WCF service:

Add Service Reference

The last is to add some code that will retrieve the data from the service and bind that data to the DataGrid.


public class ViewModel
    WCFServiceReference.ServiceClient _serviceClient = new ServiceClient();        

    public List<Employee> Employees
            return _serviceClient.GetEmployees().ToList(); 

    <DataGrid Name="dataGrid1" ItemsSource="{Binding Employees}" AutoGenerateColumns="False">
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
            <DataGridTextColumn Header="Email" Binding="{Binding Email}" />
            <DataGridTextColumn Header="Position" Binding="{Binding Position}" />
            <DataGridTextColumn Header="Age" Binding="{Binding Age}" />
This is what we'll see once we build and run the project:
WPF Client window showing result in datagrid

Download the source code (Visual Studio 2010 project).


  1. Do you know how to add a close button and functionality to a TabItem?

    1. Hi Michael, here is very elegant solution of what you looking: