【问题标题】:Binding two UIElements to the same property doesn't work properly if the property is in a singleton instance如果属性在单例实例中,将两个 UIElement 绑定到同一个属性将无法正常工作
【发布时间】:2012-06-19 18:44:09
【问题描述】:

我从来没有遇到过这个问题,但最近我注意到如果属性驻留在 Singleton 中,则双向绑定到属性不起作用。

我的意思是“其他”CheckBox 永远不会更新它的值。

关于如何使它工作的任何想法? 提前致谢!

Singleton.cs

public class Singleton : INotifyPropertyChanged
{
    private bool panelClosed;

    static Singleton()
    {
        Instance = new Singleton();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public static Singleton Instance { get; private set; }

    public bool PanelClosed
    {
        get
        {
            return this.panelClosed;
        }

        set
        {
            this.panelClosed = value;
            this.NotifyPropertyChanged("PanelClosed");
        }
    }

    private void NotifyPropertyChanged(string info)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(null, new PropertyChangedEventArgs(info));
        }
    }
}

XAML:

<CheckBox 
    Content="Check/Uncheck me" 
    Height="16" Name="checkBox1" 
    IsChecked="{Binding Source={x:Static local:Singleton.Instance}, Path=PanelClosed, 
                UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

<CheckBox 
    Content="Sanity Check" 
    Height="16" Name="checkBox2" 
    IsChecked="{Binding Source={x:Static local:Singleton.Instance}, Path=PanelClosed, 
                UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

【问题讨论】:

    标签: c# xaml binding uielement


    【解决方案1】:

    这让我有点困惑,但这是一个简单的解决方法。使用单例没有问题。

    改变

    this.PropertyChanged(null, new PropertyChangedEventArgs(info));
    

    this.PropertyChanged(this, new PropertyChangedEventArgs(info));
    

    【讨论】:

    • 哈,没想到会这样!非常感谢!
    【解决方案2】:

    我查看了您的代码并将其实现到我自己的项目中,但不幸的是它没有按预期工作。 PropertyChangedEventHandler 始终为 null,并且从未在任何地方设置。

    您是否有您的代码的副本,以便我查看它,看看我哪里出错了?

    【讨论】:

      猜你喜欢
      • 2011-04-19
      • 1970-01-01
      • 2016-04-30
      • 2020-06-14
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多