Home > database >  Why do I have to use SetProperty in all properties in Xamarin code?
Why do I have to use SetProperty in all properties in Xamarin code?

Time:11-03

I am new to Xamarin. I am working on an existing codebase with lots of pages and viewmodels. It seems to be a standard in Xamarin to always have a private variable with every public property in a view model, and to always call SetProperty in the setter. Like this:

private string _myProperty;
public string MyProperty
{
    get { return _myProperty; }
    set { SetProperty(ref _myProperty, value); }
}

What does SetProperty do? Do I need to do this for every single property, or only some? What happens if I just use a simple property with default getters and setters? Like this:

public string MyProperty { get; set; }

My guess is that it does something to do with the binding to the XAML files, and is necessary if you want your views to update when these properties are changed. But I have not seen this explained anywhere.

CodePudding user response:

you don't have to use this. But this mechanism, INotifyPropertyChanged, is what drives the data binding mechanism used by Xamarin Forms (and other Microsoft UI stacks). SetProperty basically raises an event notifying the UI that a property has changed, and if the UI is displaying that property, that it needs to refresh.

note that this

public string MyProperty;

is NOT a C# property. It's just a field. A property needs a get and/or set. Data binding only works with public properties.

Google INotifyPropertyChanged for many extensive writeups on how this interface works and how to best implement it.

A wonderful nuget package exists, Fody PropertyChanged, that will automate much of the boilerplate code involved in using INPC. It works great with Xamarin Forms.

  • Related