使用DependencyProperty进行可见性绑定
我在下面的一些简单代码中使用了ToggleButton.IsChecked属性来设置TextBlock的可见性。 它工作正常。 由于这不适合我的程序结构,我试图将另一个TextBlock的可见性绑定到“this”的DependencyProperty。 它编译很好,但它没有产生任何影响。 我做错了什么,只是不确定是什么。
XAML
C#
using System.Windows; namespace ToggleButtonTest { public partial class MainWindow : Window { static MainWindow() { FrameworkPropertyMetadata meta = new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault); ShowMoreTextProperty = DependencyProperty.Register("ShowMoreText", typeof(bool), typeof(MainWindow), meta); } public MainWindow() { InitializeComponent(); } public static readonly DependencyProperty ShowMoreTextProperty; public bool ShowMoreText { get { return (bool)GetValue(ShowMoreTextProperty); } set { SetValue(ShowMoreTextProperty, value); } } private void toggleButton_Checked(object sender, RoutedEventArgs e) { ShowMoreText = toggleButton.IsChecked.Value; } } }
编辑:
有了这个回答后,我想发布我的工作代码……
XAML
C#
using System.Windows; namespace ToggleButtonTest { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public static readonly DependencyProperty ShowMoreTextProperty = DependencyProperty.Register("ShowMoreText", typeof(bool), typeof(MainWindow), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public bool ShowMoreText { get { return (bool)GetValue(ShowMoreTextProperty); } set { SetValue(ShowMoreTextProperty, value); } } } }
ElementName
必须是元素名称。 this
不会飞。 幸运的是,你在这里有一个MainWindow
类型的元素,它带有一个ShowMoreText
属性:根Window
元素。
为Window
命名并将其用作ElementName
,如下所示:
请注意,您可以使用RelativeSource Self
执行相同操作,但我更喜欢上面的方法。
您当前设置它的方式不会将ShowMoreText设置为false。 仅当ToggleButton的IsChecked从false更改为true时,才会调用Checked处理程序。 另外,你也需要一个Unchecked的处理程序。 处理这种情况的最好方法是在ToggleButton上设置一个Binding,它将在没有任何事件处理程序的情况下完成(使用Jay的更改):
IsChecked="{Binding Path=ShowMoreText, ElementName=thisWindow}"
为您的窗口命名并将ElementName设置为该名称,而不是使用“this”。