I’m working on a Xamarin Forms project, where I have a screen divided into 2 parts, inside a single View (say DashBoardView.Xaml). One part is having some menu options and on the other part I want to load different views on menu option clicked. The dynamically views having different ViewModels registered (using XLABS MVVM) ViewFactory.
DashBoardView.Xaml
<Grid>
<Grid ColumnSpacing="0" RowSpacing="0" BackgroundColor="#404040">
// menu options having Command binded in DashboardViewModel
</Grid>
<ContentView Grid.Row="0" Grid.Column="1" BackgroundColor="White"
Content="{Binding DashboardDetailView}">
// views are binded with DashboardDetailView
// views are loaded dynamically to DashboardDetailView
(bindable property) using new Keyword when menu option
command is executed.
</ ContentView>
</Grid>
DashBoardViewModel.CS
private Command _dashboardMenuOptionCommand;
public Command DashboardMenuOptionCommand
{
get
{
return _ dashboardMenuOptionCommand?? (_dashboardMenuOptionCommand = new Command(() => {
DashboardDetailView = new ABCView();
}));
}
}
Note: ABCView is a Xaml view registered with ABCViewModel using xLab’s ViewFactory
Problem: The issue is the ABCView is getting loaded but no user interaction is happening, as in no commands binded to a label in ABCViewModel is getting called. Is there something I’m doing wrong or is there any better or optimize way to achieve the same? Please find the attached screenshot for the reference. DashboardView.xaml
Instantiating a view won't automatically instantiate a viewmodel and set it as it's binding context.
Most (if not all) MVVM Frameworks will provide you with a method to instantiate or resolve a page, which will automatically look up and hook up the appropriate viewmodel as well. Not too sure about automatically resolving a view with a viewmodel.
If not supported by your framework, you can do it yourself by instantiating your viewmodel, then assigning it to the view's binding context, before adding the view to the page.
Please note that XLabs is a dead project, I'm not too sure it's a smart idea to use it going forward, I suggest you look into current MVVM frameworks (there's a bunch) and pick one that suits your needs and looks good to you.