Introducing ObservableProperty in .NET
At some point in my daily coding, I was feeling exhausted whenever I had to write another property implementing OnPropertyChanged. Each time I had to write similar code to this one:
Of course, I’ve created code snippet to make it faster, but still. It required filling property type, name, backing name, and after all moving the code to the place where it belongs (I don’t like mixing properties with variables). So it took time. At that time, I was learning Rx.Linq. It was great, but when eg. validating the data in the ViewModel there was no easy way of doing it Rx style. My cliented wanted dynamic search. I could have used Rx in the View layer, but I like my code behind empty.
So I was thinking:
How to do it? I need an event that data has changed in ViewModel layer. We have OnPropertyChanged. Should I subscribe to it? Extend it?
After digging and thinking I decided to create ObservableProperty. The usage is quite simple:
What is ObservableProperty?
ObservableProperty is a simple generic object that implements INotifyPropertyChanged. Whenever the value changes it emits the DataChanged event, so you can subscribe to it.
You can check the full implementation in here.
How to use it?
Let’s start with the View in Xaml.
What is worth mentioning is that you should use suffix .Value to subcribe to the proper value (thinking how to fix this). As there is nothing to be done in Code Behind, so let’s go to our ViewModel.
So what happens here, is that in the constructor I am asking ViewModel to observe. In this case, I want it to observe date changes emitted by SearchText. Whenever this event is emitted, I am asking ViewModel to wait for 750 milliseconds & then perform an action like send API request.
I guess that’s all for now. This was a quick one 😈 As in always, if you have any questions or advice feel free to write a comment, drop me an email, message whatever. I will be more than happy to talk with you.
If by any chance you liked this article, show me some love and 👏! Thanks!