无法成功将 IsVisible 动态绑定到静态字段

时间:2021-07-21 23:50:57

标签: c# xamarin.forms binding

我正在尝试做一些类似于 Binding to static class property 的事情。我想将多个控件的 IsVisible 属性绑定到单个静态 bool(这样我就可以使用单个 C# 语句让它们全部出现和消失)。

这是我的其中一个控件的 XAML:

<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."/>

这里是字段:

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

我有一个测试按钮可以切换 IsChangingPassword,但控件的可见性没有改变。

我猜这与“引发 PropertyChanged 事件”有关,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

这是 WPF 4.5 中的新功能之一,它支持绑定到静态属性。它可能不适用于 Xamarin.Forms

正如Jason所说,如果您想在运行时动态更新,您需要实现INotifyPropertyChanged。但在表单中,静态类无法实现接口。

所以你应该做一些改变:

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

    }
}

在您的 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."/>

那么当您可以更改代码隐藏中的 IsChangingPassword 时,例如:

State.Current.IsChangingPassword = false;