I am creating a project in Xamarin.Forms
who implements a side menu ( Master/Detail
). So far I have been able to display the menu correctly and list some items in it, the idea is to click on one of these menu items to open another page and here is where my problem is.
Since I am using MVVM
template, my View
is binding with a ViewModel
, when I select one of the menu items it generates a exception
that I can not solve.
I'll show the code to make it clearer:
View:
<StackLayout>
<ListView x:Name="listaEmpresas"
ItemsSource="{Binding ListaMenu}"
SelectedItem="{Binding ItemSelecionado}">
<ListView.Header>
<StackLayout BackgroundColor="Gray"
WidthRequest="100"
HeightRequest="40">
<Label Text="Menu de Navegação"
TextColor="White" FontSize="18"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Center"/>
</StackLayout>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Label Text="{Binding Nome}"
FontSize="15"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Code Behind:
public partial class MasterView : ContentPage
{
public MasterViewModel ViewModel { get; set; }
public MasterView (ItensMenu menu)
{
InitializeComponent ();
this.ViewModel = new MasterViewModel();
this.BindingContext = this.ViewModel;
}
protected async override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Subscribe<ItensMenu>(this, "ItemSelecionadoMenu",
(msg) =>
{
Navigation.PushAsync(new VeiculoView());
App.MasterDetail.Detail.Navigation.PushAsync(new VeiculoView());
});
}
ViewModel:
public class MasterViewModel : BaseViewModel
{
public string teste { set; get; }
public List<ItensMenu> ListaMenu { get; set; }
public MasterViewModel()
{
this.teste = "Teste";
this.ListaMenu = new List<ItensMenu>
{
new ItensMenu {Nome = "Creditos", Id = "1" },
new ItensMenu {Nome = "Editar Perfil", Id = "2"},
new ItensMenu {Nome = "Veiculos", Id = "3"},
new ItensMenu {Nome = "Historico", Id = "4"},
new ItensMenu {Nome = "Alertas", Id = "5"}
};
}
private ItensMenu itemSelecionado;
//Pegar o valor do item Selcionado do Menu
public ItensMenu ItemSelecionado
{
get
{
return itemSelecionado;
}
set
{
itemSelecionado = value;
if (value != null)
{
MessagingCenter.Send<ItensMenu>(itemSelecionado, "ItemSelecionadoMenu");
}
}
}
}
When I click on one of the items the following exception occurs:
Unhandled Exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. occurred
One detail is that when I change the code Navigation.Async
by a DisplayAlert
in CodeBehind it works normal.