【问题标题】:Unable to successfully dynamically bind IsVisible to static field无法成功将 IsVisible 动态绑定到静态字段
【发布时间】:2021-09-29 07:29:21
【问题描述】:

我正在尝试做类似于Binding to static class property 的事情。我想将多个控件的 IsVisible 属性绑定到单个静态布尔值(这样我就可以使用单个 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 事件的引发”有关,但我不知道该怎么办。

【问题讨论】:

  • 只能绑定公共属性,不能绑定字段
  • public bool IsChangingPassword { get; set; }= true;
  • 并且,如果你想在运行时动态更新你需要实现 INotifyPropertyChanged
  • 与字段(而不是属性)的静态绑定工作得很好(除了关系是“一次性的”)。

标签: c# xamarin.forms binding


【解决方案1】:

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

正如Jason所说,如果你想在rutime动态更新,你需要实现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;

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多