42
votes

I have the following (abbreviated) xaml:

<TextBlock Text="{Binding Path=statusMsg, UpdateSourceTrigger=PropertyChanged}"/>

I have a singleton class:

public class StatusMessage : INotifyPropertyChanged
{   
    private static StatusMessage instance = new StatusMessage();

    private StatusMessage() { }

    public static StatusMessage GetInstance()
    {
        return instance;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string status)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(status));
        }
    }

    private string statusMessage;
    public string statusMsg
    {
        get
        {
            return statusMessage;
        }
        set
        {
            statusMessage = value;
            OnPropertyChanged("statusMsg");
        }
    }
}

And in my main window constructor:

StatusMessage testMessage = StatusMessage.GetInstance();
testMessage.statusMsg = "This is a test msg";    

I cannot get the textblock to display the test message. When I monitor the code through debug, the PropertyChanged is always null. Any ideas?

10
Where do you set your DataContext with a StatusMessage instance ?Jérôme Laban

10 Answers

21
votes

Thanks Jerome! Once I set the DataContext it started working as it should! I added the following to the main window constructor for testing purposes:

 this.DataContext = testMessage;
15
votes

I ran into this today and wasted some time on it, and eventually figured it out. I hope this helps save you and others some time.

If there are no subscribers to your event, and you simply declared the events as:

public event EventHandler SomeEventHappened;

Then null reference is expected. The way around this is to declare as follows:

public event EventHandler SomeEventHappened = delegate { };

This will ensure that it is not a null reference when you call as

SomeEventHappened()

Another pattern i've seen is to not initialize to delegate {} and instead check for null:

var eventToRaise = SomeEventHappened;
if( eventToRaise != null )
{
    SomeEventHappened()
}
9
votes

Your OnPropertyChanged string must exactly match the name of the property as it's case sensitive.

Try changing

OnPropertyChanged("StatusMsg");

to

OnPropertyChanged("statusMsg");

Update: Also - just noticed that you're binding to StatusMsg (capital 'S'); so the control was not binding to the property, which is another reason why it wasn't updating!

5
votes

Just in case: I had a similar problem but my mistake was that class which implemented INotifyPropertyChanged was private. Making it public resolved my case.

4
votes

in my case this make it to work:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;    // this row fixed everything
    }
    ****
    Some code here with properties etc
    ***
}
1
votes

Another point - for PropertyChanged to be null make sure you bind the object to the DataContext and then set the Path instead of directly assigning the property to the UI field.

1
votes

I also have seen the PropertyChanged event be null when I have existing data assigned to the control's data bound property:

<TextBlock Name="CarTireStatus" Text="{Binding TireStatus}" >Bad Text!</TextBlock>

Where as this works:

<TextBlock Name="CarTireStatus" Text="{Binding TireStatus}" ></TextBlock>
0
votes

There is a couple of items to check for when observing the PropertyChanged event object as null.

  1. Ensure the property name passed in as an argument when raising the event actually matches the name of the property you are targeting.

  2. Ensure that you are using only one instance of the object that contains the property you are binding to.

For item number two, this can be done by simply placing a break point on the class constructor for the object that harbors the property that is being bound. If the breakpoint is triggered more than once, then you have a problem and need to resolve the number of instances of objects to only one instance that your runtime invokes via XAML.

Thus, it's better to implement that class as a singleton pattern so that you can ensure just one instance of the object at runt-time.

-1
votes

I had a similar issue, neither solutions above helped me. All I needed to do was to use the built c# Propertychanged. Beforehand I have implemented propertyChanged (by an accident) and it pointed at nothing.

-3
votes

If you follow all instructions, verifying your property name is correct, that it is correctly being assigned a new value, you are using a singleton to guarantee one instance of you view model, and you have successfully assigned your DataContext in the UI - make sure that whatever is forcing your property to update is done after the visual tree has been completed, i.e. move the refresh of your property to a button, rather than say the Loaded event of your window. I say this because I had the same issue, and found that when I refreshed my view model data property from my Infragistics NetAdvantage ribbon window's Loaded event, my PropertyChanged event was always null.