微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决无法成功将 IsVisible 动态绑定到静态字段

我正在尝试做一些类似于 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 事件”有关,但我不知道该怎么做。

解决方法

这是 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?