Try using
await Application.Current.MainPage.Navigation.PushAsync(new Page1());
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
So I'm currently trying to display a new page when clicking an item using MVVM in my ListView
but it's not doing anything when I click an item.
The way I've set things up is by first changing my MainPage.xaml
. Adding a ListView
and settings the BindingContext
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MultiplePages.MainPage"
xmlns:viewModel="clr-namespace:MultiplePages.MVVM.ViewModel">
<ContentPage.BindingContext>
<viewModel:MainViewModel/>
</ContentPage.BindingContext>
<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
I then made sure to update the constructor inside App.cs
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
I then created the ContentPage
that was going to be displayed when I clicked an Item
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MultiplePages.MVVM.View.Page1">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
And finally, I setup the ViewModel
class MainViewModel : ContentPage
{
public ObservableCollection<Item> Items { get; set; }
private Item _selectedItem;
public Item SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
if (_selectedItem == null)
{
return;
}
ShowMessage(_selectedItem);
SelectedItem = null;
}
}
public MainViewModel()
{
Items = new ObservableCollection<Item>();
for (int i = 0; i < 10; i++)
{
Items.Add(new Item { Name = $"Item {i}" });
}
}
private async void ShowMessage(Item item)
{
await Navigation.PushAsync(new Page1());
}
}
The goal was to call ShowMessage
when then SelectedItem
changed, aka when I clicked a new item in the ListView
but nothing happens.
I've made sure to check that SelectedItem
is bound properly by setting a breakpoint and I know for sure that ShowMessage()
gets invoked everytime I click an Item.
Why is it not reacting?
Try using
await Application.Current.MainPage.Navigation.PushAsync(new Page1());