简体   繁体   English

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

[英]How to bind a WPF control to the code behind?

I have this XAML: 我有这个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. IsExpanded属性的Binding表达式不起作用。 This code is a simplification, in reality the expander's binding is already set through the datacontent of a parent control. 这段代码是一种简化,实际上扩展器的绑定已经通过父控件的datacontent设置。
How can I bind the IsExpanded property to a property of the code behind? 如何将IsExpanded属性绑定到后面代码的属性?
Can I bind it to the result of a method in the code behind? 我可以将它绑定到后面的代码中的方法的结果吗?

The source for the binding is a RelativeSource.Self . 绑定的源是RelativeSource.Self That means the source is the Expander rather than the Window . 这意味着源是Expander而不是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}"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM