2

I have never come across this issue but most recently I noticed that a two way binding to a property doesn't work if the property resides in a Singleton.

What I mean is that the 'other' CheckBox never updates its value.

Any ideas on how to make it work? Thanks in advance!

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}" />
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Austin
  • 33
  • 4

2 Answers2

0

This had me confused for a bit, but it's a simple fix. There's no problem using a singleton.

Change

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

to

this.PropertyChanged(this, new PropertyChangedEventArgs(info));
Phil
  • 42,255
  • 9
  • 100
  • 100
0

I've had a look at your code and implemented it into my own project, but unfortunately it's not working as intended. The PropertyChangedEventHandler is always null and isn't ever set up anywhere.

Do you have a copy of your code so that I can have a look at it and see where I am going wrong?

James Croft
  • 1,680
  • 13
  • 25