tags:

views:

1327

answers:

3

This walkthrough says you can create a WPF datagrid in one line but doesn't give a full example.

So I created an example using a generic list and connected it to the WPF datagrid, but it doesn't show any data.

What do I need to change on the code below to get it to show data in the datagrid?

ANSWER:

This code works now:

XAML:

<Window x:Class="TestDatagrid345.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
    xmlns:local="clr-namespace:TestDatagrid345"
    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
    <StackPanel>
        <toolkit:DataGrid ItemsSource="{Binding}"/>
    </StackPanel>
</Window>

Code Behind:

using System.Collections.Generic;
using System.Windows;

namespace TestDatagrid345
{
    public partial class Window1 : Window
    {
        private List<Customer> _customers = new List<Customer>();
        public List<Customer> Customers { get { return _customers; }}

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = Customers;

            Customers.Add(new Customer { FirstName = "Tom", LastName = "Jones" });
            Customers.Add(new Customer { FirstName = "Joe", LastName = "Thompson" });
            Customers.Add(new Customer { FirstName = "Jill", LastName = "Smith" });
        }
    }
}
+2  A: 

You need to add

DataContext = Customers;

In your Window_Loaded()

rudigrobler
I added DataContext = Customers to Window_Loaded() but the datagrid still displays no data. I'm quite sure I've done this binding before with a generic list, and I thought the Datagrid just read the fields of the generic object out. I'm using the March 2009 version of the Toolkit.
Edward Tanguay
+1  A: 

Now remove the Path=Customers from your binding, and it should work :)

Arcturus
no that still doesn't work, I reposted the current code that doesn't work above.
Edward Tanguay
You still need the Binding... like so: ItemsSource={Binding}
Arcturus
A: 

try it: populate you _customers list and asign property ItemsSource

        dataGrid1.ItemsSource = _customers;
lepumin