Guetguet
Guetguet

Reputation: 27

Why is staticpropertychanged null?

I develop an UWP application. I have a class Client which manage the connection to another application by sockets.

In my ViewModel class, I have a static property named TextConnect which is bind to a textbox in my View.

I want to display "Connected" in the textbox when the connection is established. So, my ViewModel class implement INotifyPropertyChanged, and I have a static EventHandler named StaticPropertyChanged that I used to notify the view that my TextConnect property changed :

public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;

And in my Client class I changed the value of this property when the connection is established :

ViewModel.TextConnect = "Connected";

The method which modifies the TextConnect property in my Client class runs in another thread.

But when I try to change the value of the property, I have an error which says that my event StaticPropertyChanged is null :

System.NullReferenceException : 'Object reference not set to an instance of an object.'

Why StaticPropertyChanged is null while my property is bind to my textbox ?

Upvotes: 0

Views: 312

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32775

I want to display "Connected" in the textbox when the connection is established. So, my ViewModel class implement INotifyPropertyChanged, and I have a static EventHandler named StaticPropertyChanged

If you want bind TextBox Text property with ViewModel's TextConnect property, TextConnect should be non-static, because we need to invoke PropertyChanged in the set method (can not run in the static method). If you want to access TextConnect statically, you could make static Current property for the ViewModel. For the detail steps please refer the following code.

Xaml

<ToggleSwitch Header="This is header" IsOn="{Binding IsOpen}" />

ViewModel

public class MainPageViewModel : INotifyPropertyChanged
{
    public static MainPageViewModel Current;
    public MainPageViewModel()
    {
        Current = this;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName]string name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
    private bool _isOpen;

    public bool IsOpen
    {
        get { return _isOpen; }
        set { _isOpen = value; OnPropertyChanged(); }
    }
}

Usage

MainPageViewModel.Current.IsOpen = true;

Upvotes: 1

Related Questions