-1

I am trying to do something similar to Binding to static class property. I want to bind the IsVisible property of multiple controls to a single static bool (so I can make them all appear and disappear with a single C# statement).

Here is my XAML for one of the controls:

<Label Grid.Row="3"
       x:Name="LabelDireWarning"
       Grid.ColumnSpan="2"
       TextColor="Red"
       FontAttributes="Bold"
       HorizontalTextAlignment="Center"
       IsVisible="{Binding Source={x:Static local:State.IsChangingPassword}}"
       Text="blah blah."/>

Here is the field:

public static class State
{
    public static bool IsChangingPassword = true;
    etc.

I have a test button that toggles IsChangingPassword, but the visibility of the control does not change.

I guess this has to do with "the raising of the PropertyChanged event," but what should I to do?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Charles
  • 479
  • 1
  • 3
  • 13

1 Answers1

0

This is one of the new features in WPF 4.5 that it is supporting for binding to static properties. It may not work for Xamarin.Forms.

And as Jason said, you need to implement INotifyPropertyChanged if you want to dynamically update at run time. But in forms, the static class could not implement the interface.

So you should make some changes:

public static class State
{

    private static Status g_Current = new Status();

    public static Status Current
    {
        get
        {
            return g_Current;
        }
    }

    public class Status : INotifyPropertyChanged
    {
        public  event PropertyChangedEventHandler PropertyChanged;

        private  bool _isChangingPassword = true;

        public  bool IsChangingPassword
        {
            get { return _isChangingPassword; }

            set
            {
                if (value != _isChangingPassword)
                {
                    _isChangingPassword = value;

                    NotifyPropertyChanged("IsChangingPassword");
                }
            }
        }


        protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

In your XAML:

<Label Grid.Row="3"
       x:Name="LabelDireWarning"
       Grid.ColumnSpan="2"
       TextColor="Red"
       FontAttributes="Bold"
       HorizontalTextAlignment="Center"
       IsVisible="{Binding Source={x:Static local:State.Current}, Path=IsChangingPassword}"
       Text="blah blah."/>

And then when you could change the IsChangingPassword in your code-behind like:

State.Current.IsChangingPassword = false;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Leo Zhu
  • 15,726
  • 1
  • 7
  • 23