Issue
I'm trying to dynamically create tabs for a iOS app.
I've passed through a variable, with shell navigation, that loads items from a database for which we create a tab for each object.
The problem I have is that the codebehind runs before the shell navigation has passed the variable from the viewmodel to the codebehind.
Viewmodel:
{
[QueryProperty(nameof(Number), nameof(Number))]
public class TabbedPageViewModel : BaseViewModel
{
private int _Number;
public TabbedPageViewModel()
{
}
public int Number
{
get => _Number;
set => SetProperty(ref _Number, value);
}
}
Codebehind:
public partial class TabbedPage : TabbedPage
{
TabbedPageViewModel _viewModel;
public TabbedPage()
{
BindingContext = _viewModel = new TabbedPageViewModel();
InitializeComponent();
LoadTabs();
}
private void LoadTabs()
{
var results = Database.GetAsync(_viewModel.Number).Result;
foreach (var _result in results)
{
var from = _result.A;
var to = _result.B;
var _title = from + "-" + to;
this.Children.Add(new ContentPage { Title = _title });
}
}
}
How can I delay the codebehind so that the shell navigation sets the Number variable before LoadTabs() runs?
Solution
I ended up using Messaging Center:
CodeBehind
public TabbedPage()
{
InitializeComponent();
BindingContext = _viewModel = new TabbedPageViewModel();
MessagingCenter.Subscribe<TabbedPageViewModel>(this, "NumberChanged", (sender) =>
{ LoadTabs(); }
);
}
ViewModel:
public int Number
{
get => _number;
set
{
SetProperty(ref _number, value);
MessagingCenter.Send<TabbedPageViewModel>(this, "NumberChanged");
}
}
Answered By - Aaron
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.