title: How to set the datacontext of a user control
body: <p>I'm writing an application in WPF, using the MVVm toolkit and have problems with hooking up the viewmodel and view.</p>
  
  <p>The model is created with ado.net entity framework.</p>
  
  <p>The viewmodel:</p>
  
  <pre><code>public class CustomerViewModel
      {
          private Models.Customer customer;
          //constructor
          private ObservableCollection&lt;Models.Customer&gt; _customer = new ObservableCollection&lt;Models.Customer&gt;();
          public ObservableCollection&lt;Models.Customer&gt; AllCustomers
          {
              get { return _customer; }
  
          }
          private Models.Customer _selectedItem;
          public Models.Customer SelectedItem
          {
              get { return _selectedItem; }
  
          }
          public void LoadCustomers()
          {
              List&lt;Models.Customer&gt; list = DataAccessLayer.getcustomers();
              foreach (Models.Customer customer in list)
              {
                  this._customer.Add(customer);
              }
              }
          }
  </code></pre>
  
  <p>And the view (no code behind at the moment):</p>
  
  <pre><code>&lt;UserControl x:Class="Customers.Customer"
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
               xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
               mc:Ignorable="d" 
               xmlns:vm ="clr-namespace:Customers.ViewModels"
               d:DesignHeight="300" d:DesignWidth="300"
               xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" &gt;
  
      &lt;Grid&gt;
          &lt;toolkit:DataGrid ItemsSource="{Binding AllCustomers}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AutoGenerateColumns="True"&gt;
  
          &lt;/toolkit:DataGrid&gt;
  
          &lt;toolkit:DataGrid ItemsSource="{Binding SelectedItem.Orders}"&gt;
  
          &lt;/toolkit:DataGrid&gt;
  
  
  
      &lt;/Grid&gt;
  &lt;/UserControl&gt;
  </code></pre>
  
  <p>And dataaccesslayer class:</p>
  
  <pre><code> class DataAccessLayer
      {
          public List&lt;Customer&gt; customers = new List&lt;Customer&gt;();
  
          public static List&lt;Customer&gt; getcustomers()
          {
              entities db = new entities();
  
              var customers = from c in db.Customer.Include("Orders")
                             select c;
              return customers.ToList();
          }
  
  
      }
  </code></pre>
  
  <p>The problem is that no data is displayed simply because the data context is not set. I tried to do it in a code-behind but is did not work. I would prefer to do it in a xaml file anyway. Another problem is with the SelectedItem binding - the code is never used.</p>