I'm new to Xamarin world, and its data binding rules. I have ViewModel with observable CurrentOrder property, and 3 properties which values depend on it. All 4 properties are used in View with bindings, so that each change in CurrentOrder should propagate changes to other 3 properties and that impact how view displays its controls and data. I'm confused with how I'm supposed to propagate the signal of CurrentOrder change to other 3 dependent properties. I came up with code that actually works, but to me it looks a bit awkward, and sets dependency inside independent property CurrentOrder, while I would prefer it to be other way around: dependent properties should better know what property they depend on.
Please note that SetProperty and OnPropertyChanged methods are in a base view model, and generated by standard VS Xamarin.Forms project pattern.
private int _currentOrder = 1;
public int CurrentOrder
{
get => _currentOrder;
set => SetProperty(ref _currentOrder, value, onChanged: () =>
{
OnPropertyChanged(nameof(CurrentItem));
OnPropertyChanged(nameof(IsTheLastItem));
OnPropertyChanged(nameof(IsTheFirstItem));
});
}
public string CurrentItem => Items[CurrentOrder - 1];
public bool IsTheLastItem => CurrentOrder == Items.Count;
public bool IsTheFirstItem => CurrentOrder == 1;
Any recommendations over best practices here are very appreciated
I would use Fody propertychanged for dependent properties like this.
Just add the nuget and dont forget to add FodyWeavers.xml, your class will be like below
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int CurrentOrder {get; set;}
public string CurrentItem => Items[CurrentOrder - 1];
public bool IsTheLastItem => CurrentOrder == Items.Count;
public bool IsTheFirstItem => CurrentOrder == 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With