views:

1055

answers:

1

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?

+4  A: 

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}"/>

HTH, Kent

Kent Boogaart
Great, thanks a bunch!
Dabblernl