title: How to bind a WPF control to the code behind?
body: <p>I have this XAML:</p>
  
  <pre><code>&lt;Window x:Class="WpfBindToCodeBehind.Window1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Window1" Height="300" Width="300"
      Loaded="Window_Loaded"&gt;
      &lt;StackPanel Orientation="Vertical"&gt;
          &lt;Button Name="ToggleExpand" Click="ToggleExpand_Click"&gt;Toggle Expander&lt;/Button&gt;
          &lt;Expander Name="Expander"
                    Header="Don't click me, click the button!"
                    IsExpanded="{Binding RelativeSource={RelativeSource Self},Path=MayExpand}"&gt;
              &lt;TextBlock Text="{Binding}"/&gt;
          &lt;/Expander&gt;
      &lt;/StackPanel&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>This is the code behind:</p>
  
  <pre><code>public partial class Window1 : Window,INotifyPropertyChanged 
      {
          public event PropertyChangedEventHandler PropertyChanged;
  
          public Window1()
          {
              InitializeComponent();
          }
  
          private void ToggleExpand_Click(object sender, RoutedEventArgs e)
          {
              MayExpand = !mayExpand;
          }
  
          private void Window_Loaded(object sender, RoutedEventArgs e)
          {
              Expander.DataContext = "Show me";
          }
  
          private bool mayExpand;
          public bool MayExpand
          {
              get { return mayExpand; }
              set
              {
                  mayExpand = value;
                  if (PropertyChanged != null)
                      PropertyChanged(this, new PropertyChangedEventArgs("MayExpand"));
              }
          }
      }
  </code></pre>
  
  <p>The Binding expression for the IsExpanded property is not working. This code is a simplification, in reality the expander's binding is already set through the datacontent of a parent control.<br>
   <strong>How can I bind the IsExpanded property to a property of the code behind?</strong><br>
  <strong>Can I bind it to the result of a method in the code behind?</strong></p>