C#中PropertyChanged事件为何会为null?MVVM场景技术疑问
PropertyChanged Can Be Null in MVVM (Xamarin.Forms) Great question—this is a super common point of confusion when you’re getting started with MVVM and .NET events! Let’s break this down clearly so it makes sense.
Declaring an event doesn’t automatically give it subscribers
When you writepublic event PropertyChangedEventHandler PropertyChanged;, you’re only defining that the event exists—you aren’t creating any subscriptions to it by default. Think of it like declaring aList<string>variable without initializing it: the variable is there, but it’s stillnulluntil you add items (or in this case, until code subscribes to the event).Common scenarios where
PropertyChangedis null- When your ViewModel is first instantiated, before it’s bound to a Xamarin.Forms Page or View. No View has hooked into the event yet, so it stays null.
- If a View that was subscribed to the event gets unloaded (like when the user navigates away from a Page and the View is disposed), and there are no other subscribers left, the event will revert to null.
- In unit tests, if you’re testing the ViewModel in isolation without attaching a View, there will be zero subscribers to the event.
Why null checks matter (and how to simplify them)
If you try to invoke a null event, you’ll hit aNullReferenceExceptionat runtime. That’s why older MVVM code often included explicit checks:if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("PropertyName")); }These days, C# 6+ lets you use the null-conditional operator to do this safely in one line:
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("PropertyName"));This does the null check behind the scenes and only runs the invoke if there are active subscribers.
To wrap it up: the event declaration just makes it available to be subscribed to—it doesn’t guarantee anyone is listening. The null check is a simple safeguard against crashes when no code is waiting for property change notifications.
内容的提问来源于stack exchange,提问作者Nimral

