.net – How to define the own columns in a WPF DataGrid

linq-to-sqlnetxaml

I've got an AutoGenerateColumns WPF-DataGrid getting bound in code-behind to LINQ-to-SQL, which works fine.

But when I take off the AutoGenerateColumns and define my own columns, it tells me "The items collection must be empty before using ItemsSource."

But I'm not binding the ItemSource in my XAML so I don't see why it isn't empty. What do I need to change so that I can define my own columns?

XAML:

<UserControl x:Class="TestDataGrid566.AppPages.ManageCustomers"
             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"
             Loaded="UserControl_Loaded">
    <toolkit:DataGrid x:Name="TheDataGrid" 
                      CanUserAddRows="False"
                      AlternatingRowBackground="#ddd"
                      CanUserSortColumns="true"
                      PreviewKeyDown="TheDataGrid_PreviewKeyDown"
                      AutoGenerateColumns="False"
                      RowEditEnding="TheDataGrid_RowEditEnding">

        <toolkit:DataGridTextColumn Header="Contact Name" Width="SizeToCells"  
                                    Binding="{Binding ContactName}" 
                                    IsReadOnly="False"/>
    </toolkit:DataGrid>
</UserControl>

code-behind:

public partial class ManageCustomers : UserControl
{
    private NorthwindDataContext _db = new NorthwindDataContext();

    public ManageCustomers()
    {
        InitializeComponent();
    }

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        LoadData();
    }

    public void LoadData()
    {
        var customers = from c in _db.Customers
                        select c;
        TheDataGrid.ItemsSource = customers.ToList();
    }
}

Best Answer

You're trying to put the column directly into the DataGrid (therefore it's trying to put the column in the grid's Items collection and that explains your error). You need to put it inside the Columns collection:

<toolkit:DataGrid x:Name="TheDataGrid" 
                          CanUserAddRows="False"
                          AlternatingRowBackground="#ddd"
                          CanUserSortColumns="true"
                          PreviewKeyDown="TheDataGrid_PreviewKeyDown"
                          AutoGenerateColumns="False"
                          RowEditEnding="TheDataGrid_RowEditEnding">
    <toolkit:DataGrid.Columns>        
        <toolkit:DataGridTextColumn Header="Contact Name" Width="SizeToCells"  
                                       Binding="{Binding ContactName}" 
                                       IsReadOnly="False"/>
    </toolkit:DataGrid.Columns>
</toolkit:DataGrid>