How to bind a WPF control to the code behind?

code-behind, data-binding, wpf

Solution

The source for the binding is a `RelativeSource.Self`. That means the source is the `Expander` rather than the `Window`. Something like this will work:

IsExpanded="{Binding MayExpand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}"

You could also use a name to simplify things:

<Window x:Name="_root">
    <Expander IsExpanded="{Binding MayExpand, ElementName=_root}"/>

Problem

I have this XAML: ``` <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"> <StackPanel Orientation="Vertical"> <Button Name="ToggleExpand" Click="ToggleExpand_Click">Toggle Expander</Button> <Expander Name="Expander" Header="Don't click me, click the button!" IsExpanded="{Binding RelativeSource={RelativeSource Self},Path=MayExpand}"> <TextBlock Text="{Binding}"/> </Expander> </StackPanel> </Window> ``` This is the code behind: ``` 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")); } } } ``` 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. How can I bind the IsExpanded property to a property of the code behind? Can I bind it to the result of a method in the code behind?

Original source