title: How to access objects in code from XAML
body: <p>I am new to WPF and am trying to understand how to use data binding to bind the controls on my window to objects in my code behind. I see several questions about accessing XAML objects from the codebehind, but that's not what I'm looking for. I already know how to do that.</p>
  
  <pre><code>label1.Content = LabelText;
  listbox1.ItemsSource = ListItems;
  </code></pre>
  
  <p>I have also seen answers about how to access a class in the codebehind from XAML.</p>
  
  <pre><code>&lt;local:MyClass x:Key="myClass" /&gt;
  </code></pre>
  
  <p>But I don't see how to apply that to a specific instance of the class. Here is an example of what I'm trying to do. The 'Bindings' are obviously incorrect. That is what I need help with.</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      private string _labelText;
      private List&lt;string&gt; _listItems = new List&lt;string&gt;();
  
      public MainWindow()
      {
          InitializeComponent();
  
          _labelText = "Binding";
          _listItems.Add("To");
          _listItems.Add("An");
          _listItems.Add("Object");
      }
  
      public string LabelText
      {
          get { return _labelText; }
          set { _labelText = value; }
      }
  
      public List&lt;string&gt; ListItems
      {
          get { return _listItems; }
          set { _listItems = value; }
      }
  }
  
  &lt;Window x:Class="SO_Demo.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="SO Demo" Height="160" Width="225"&gt;
    &lt;Grid DataContext="MainWindow"&gt;
      &lt;Label x:Name="label1" Width="80" Height="25" Margin="12,12,0,0" 
             Content="{Binding Path=LabelText}"
             HorizontalAlignment="Left" VerticalAlignment="Top" /&gt;
      &lt;ListBox x:Name="listbox1" Width="100" Height="60" Margin="12,44,0,0" 
               ItemsSource="{Binding Path=ListItems}" DisplayMemberPath="ListItems"
               HorizontalAlignment="Left" VerticalAlignment="Top" /&gt;
    &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>The books and tutorials I have read make it sound like this should be very simple. What am I missing?</p>