如何将WPF控件绑定到后面的代码?

时间:2009-08-20 21:10:39

标签: wpf data-binding code-behind

我有这个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>

这是背后的代码:

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"));
            }
        }
    }

IsExpanded属性的Binding表达式无效。这段代码是一种简化,实际上扩展器的绑定已经通过父控件的datacontent设置了  如何将IsExpanded属性绑定到后面代码的属性?
我可以将其绑定到后面代码中方法的结果吗?

1 个答案:

答案 0 :(得分:10)

绑定的来源是RelativeSource.Self。这意味着来源是Expander而不是Window。这样的事情会起作用:

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

您还可以使用名称来简化操作:

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