title: How can I define my own columns in a WPF DataGrid?
body: <p>I've got an <code>AutoGenerateColumns</code> WPF-DataGrid getting bound in code-behind to LINQ-to-SQL, which works fine.</p>
  
  <p>But when I take off the <code>AutoGenerateColumns</code> and define my own columns, it tells me "<em>The items collection must be empty before using ItemsSource.</em>"</p>
  
  <p>But I'm not binding the <code>ItemSource</code> in my XAML so I don't see why it isn't empty. <strong>What do I need to change so that I can define my own columns?</strong></p>
  
  <p><strong>XAML:</strong></p>
  
  <pre><code>&lt;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"&gt;
      &lt;toolkit:DataGrid x:Name="TheDataGrid" 
                        CanUserAddRows="False"
                        AlternatingRowBackground="#ddd"
                        CanUserSortColumns="true"
                        PreviewKeyDown="TheDataGrid_PreviewKeyDown"
                        AutoGenerateColumns="False"
                        RowEditEnding="TheDataGrid_RowEditEnding"&gt;
  
          &lt;toolkit:DataGridTextColumn Header="Contact Name" Width="SizeToCells"  
                                      Binding="{Binding ContactName}" 
                                      IsReadOnly="False"/&gt;
      &lt;/toolkit:DataGrid&gt;
  &lt;/UserControl&gt;
  </code></pre>
  
  <p><strong>code-behind:</strong></p>
  
  <pre><code>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();
      }
  }
  </code></pre>