Binding Visibility in XAML to a Visibility propert

2019-03-27 19:11发布

I've seen on the internet quite a few examples of binding a boolean to the Visibility property of a control in XAML. Most of the good examples use a BooleanToVisibiliy converter.

I'd like to just set the Visible property on the control to bind to a System.Windows.Visibility property in the code-behind, but it doesn't seem to want to work.

This is my XAML:

<Grid x:Name="actions" Visibility="{Binding Path=ActionsVisible, UpdateSourceTrigger=PropertyChanged}" />

This is the code for the property:

private Visibility _actionsVisible;
public Visibility ActionsVisible
{
   get
   {
      return _actionsVisible;
   }
   set
   {
      _actionsVisible = value;
   }
}

In the constructor of the Window, I also have this call:

base.DataContext = this;

When I update either ActionsVisible or this.actions.Visibility, the state doesn't transfer. Any ideas to what might be going wrong?

3条回答
We Are One
2楼-- · 2019-03-27 19:37

Write: NotifyPropertyChanged("ActionsVisible")

查看更多
smile是对你的礼貌
3楼-- · 2019-03-27 19:42

I think the problem is that WPF can't know that your ActionsVisible property has changed since you've not notified the fact.

Your class will need to implement INotifyPropertyChanged, then in your set method for ActionsVisible you'll need to fire the PropertyChanged event with ActionsVisible as the property name that has changed.

Hope this helps...

查看更多
倾城 Initia
4楼-- · 2019-03-27 19:51

Change your property to be a DependencyProperty. This will handle the updating for you.

        public Visibility ActionsVisible
    {
        get { return (Visibility)GetValue(ActionsVisibleProperty); }
        set { SetValue(ActionsVisibleProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ActionsVisible.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ActionsVisibleProperty =
        DependencyProperty.Register("ActionsVisible", typeof(Visibility), typeof(FooForm));
查看更多
登录 后发表回答