Reputation: 5072
I have a Xamarin Forms app where I use the Master-Detail template, in combination with MVVM. It suites my needs quite well. The thing is that I would occasionally show some sort of information in a notification-like style in the top bar of the displayed view. This would sometimes be an error message like "Server not reachable" or "Action not allowed".
The thing is that it seems the only way to put something into that bar is via the ContentPage.ToolbarItems
, which does not have a DataBinding or any way to be accessed via the ViewModel.
A possible solution I came up with is passing the view as an argument to the ViewModel, and from there do something like view.ToolbarItems.Add(new ToolbarItem("abc", null, () => { }));
. But this is breaking the MVVM on a quite basic level, as the ViewModel has a reference to the View. It would be possible to mask the view with an interface, but I don't like this solution at all.
So, can I use DataBinding to dynamically add and remove a button to the top bar in a Xamarin Master-Detail app?
Upvotes: 1
Views: 120
Reputation: 2129
As you have already mentioned, it is never a good idea to have a reference to the view in the viewmodel because it breaks the MVVM pattern. In cases like yours, when binding is not available, a sensible/acceptable approach is to subscribe to the viewmodel from the view in order to update it if the viewmodel changes.
Add something like this to your view:
ViewModel.PropertyChanged += OnViewModelPropertyChanged;
...
private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(ViewModel.YourProperty):
// Apply changes to the view here, for example:
ToolbarItems.Add(new ToolbarItem(ViewModel.YourProperty, null, () => { }));
break;
}
}
I hope this helps!
Upvotes: 1