Navigate Content Pages MVVM xamarin - c#

Can someone teach me how to navigate between pages of content? I have been reading many tutorials but I have not been able to achieve it. I have this small code I want to achieve that when pressing the buttons I change between the pages. I use MVVM model there is my MainViewModel
public class MainViewModel
{
public Page1 PageNumberOne { get; set; }
public Page2 PageNumberTwo { get; set; }
public MainViewModel()
{
this.PageNumberOne = new Page1();
}
}
there is my view model of Page1
public class Page1
{
#region constructor
public Page1()
{
GoPage2Command = new Command(async () => await GoPage2());
}
private async Task GoPage2()
{
await Application.Current.MainPage.DisplayAlert("", "Goin to page 2", "ok");
//code to go PageNumberTwo here
}
#endregion
#region Commands
public Command GoPage2Command { get; set; }
#endregion
}
GoPage2Command is binding to a button.
there is my complete project up load to MF VS proyect

Simply call
Navigation.PushAsync(new ContentPage());
INavigation.PushAsync Method
Asynchronously adds a Page to the top of the navigation stack.
Example from the page
var newPage = new ContentPage ();
await Navigation.PushAsync (newPage);
Debug.WriteLine ("the new page is now showing");
var poppedPage = await Navigation.PopAsync ();
Debug.WriteLine ("the new page is dismissed");
Debug.WriteLine (Object.ReferenceEquals (newPage, poppedPage)); //prints "true"
Your Exmaple
private async Task GoPage2()
{
await Application.Current.MainPage.DisplayAlert("", "Goin to page 2", "ok");
//code to go PageNumberTwo here
Navigation.PushAsync(new PageNumberTwo());
}

I found the problem, I was using Xamarin Live to do the tests, connecting by cable does not give any error. I do not recommend using Xamarin Live not only gives that problem but many more

Related

Why doesn't navigation work for me after calling Navigation.InsertPageBefore() in Xamarin Forms?

I'm trying to implement logging in on Xamarin Forms (5.0.0, using ActiveDirectory's built in Login page). Any ideas on how to make this work?
In the constructor of App.xaml.cs, I have:
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new LoginPage());
}
I implement the Login page w/ a view model, in which I pass in a callback that should (according to the documentation), set my navigation root to my HomePage:
public partial class LoginPage : ContentPage
{
private async Task _handleLoginAsync()
{
Navigation.InsertPageBefore(new HomePage(), this);
await Navigation.PopAsync();
}
public LoginPage()
{
InitializeComponent();
BindingContext = new LoginPageViewModel(_handleLoginAsync);
}
}
In the view model, I try to login using Device.BeginInvokeOnMainThread, calling my(note, I didn't include login logic for brevity/cleanliness)
public Command LoginCommand => new Command(LoginUsingAzureAsync);
private Func<Task>_handleLoginAsync;
public LoginPageViewModel(Func<Task> handleLoginAsync)
{
_handleLoginAsync = handleLoginAsync;
LoginCommand.Execute(null);
}
internal void LoginUsingAzureAsync()
{
Device.BeginInvokeOnMainThread(async () =>
{
try
{
if (await Login()) == true)
{
UserDialogs.Instance.HideLoading();
await _handleLoginAsync();
return;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
UserDialogs.Instance.Alert("The login has failed.");
}
});
}
It successfully goes to the homepage, but navigating to other pages afterwards doesn't work. When I call the following, it enters the OtherPage() constructor, but fails to render the new page.
Navigation.PushAsync(new OtherPage());
Note, the navigation works as expected if I use PushAsync(new HomePage()) rather than removing the login, but I'd prefer to remove the login page from the navigation stack.
Thanks in advance!
Update: Here's the initial HomeViewModel:
public class HomeViewModel
{
private readonly INavigation _navigation;
public Command GoToOtherPageCommand => new Command(GoToOtherPage);
public async void GoToOtherPage()
{
await App.Navigation.PushAsync(new OtherPage());
}
}
The problem wasn't in the login, it was in the HomePageViewModel, which was initially referencing App.Navigation (see update in question).
Passing in the navigation into my ViewModel did the trick:
public class HomeViewModel
{
private readonly INavigation _navigation;
public Command GoToOtherPageCommand => new Command(GoToOtherPage);
public async void GoToOtherPage()
{
await _navigation.PushAsync(new OtherPage());
}
public HomeViewModel(INavigation navigation)
{
_navigation = navigation;
}
}
public partial class HomePage : ContentPage
{
public HomePage()
{
InitializeComponent();
BindingContext = new HomeViewModel(Navigation);
}
}

Xamarin forms : bug in master detail Page

I have a bug in my Xamarin Forms app. When I was coding page to appear content "master-detail" when the user chose on the last page. The content doesn't appear.
During debugging, the app work without any code errors; however, it appears without any content. I am using the Firebase database.
Firebase helper:
public async Task<List<Cuts>> GetAction()
{
return (await firebase
.Child("Action")
.OnceAsync<Cuts>()).Select(item => new Cuts
{
name = item.Object.name,
link = item.Object.link,
poster = item.Object.poster
}).ToList();
}
The page which the users choose from:
public partial class ActionFilms : ContentPage
{
FirebaseHelper firebaseHelper = new FirebaseHelper();
public ActionFilms()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();
var allPersons = await firebaseHelper.GetAction();
act.ItemsSource = allPersons;
}
public void act_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var acctionn = e.PreviousSelection as Cuts;
App.Current.MainPage.Navigation.PushAsync(new ActionMaster(acctionn));
}
}
The code of master-detail Page "which the content does not appear at here":
public partial class ActionMaster : ContentPage
{
public ActionMaster(Cuts acctionn)
{
BindingContext = acctionn;
InitializeComponent();
}
}

blank page when using pushasync xamarin

how are you?
I created a top ContentPage class inheriting a ZXingScannerPage class to be able to create methods in order to better streamline the code. And in it a method that takes as a parameter a Label and a ContentPage to set the data read by the Scanner.
public String ScannResult { get; set; }
}
public class ScannerHelper : ZXingScannerPage
{
public ScannerHelper()
{
this.OnScanResult += (result) => {
MessagingCenter.Send( new Message { ScannResult = result.Text }, "ScannResult");
// Parar de escanear
this.IsScanning = false;
// Alert com o código escaneado
Device.BeginInvokeOnMainThread(() => {
DisplayAlert("Código escaneado", result.Text, "OK");
Navigation.PopAsync(false);
});
};
}
public static void teste(Label label, ContentPage contentPage)
{
MessagingCenter.Subscribe<Message>(contentPage, "ScannResult", message => {
label.Text = message.ScannResult;
});
}
}
}
So far everything is working, but when I call this class on a button and run it later, the screen takes the data and goes to the label, but when going to another page with a PushAsync the page is blank and if I go back to the pages and try to go to the next one it is blank and the strangest thing if I leave the app on my cell phone going to the menu and returning to it the page is normal. Example: Page A calls the Scanner and works, on Page A I go to Page B and it is blank, I go back to Page A and I go back to the page before Page A and then I go back to A to A and now it is in White.
Example of how I use the Methods on the buttons and on the page:
{
InitializeComponent();
ScannerHelper.teste(lblNomeProduto, this);
}
private void ButtonScanner(object sender, EventArgs e)
{
Navigation.PushAsync(new ScannerHelper());
}

Xamarin portable, how to navigate back from selected list item to MainPage and pass value

My previous question was, how to navigate from ToolbarItem to another page and keep navigation bar existing. : Xamarin portable project navigate with ToolbarItem to another page by using MasterDetailPage
Now I have troubles when I select item from item list and I want to back to my MainPage, but I am getting such a error: System.Exception: Android only allows one navigation page on screen at a time and MainPage page appear, but it freeze and I see now 2 buttons on navigation bar. But it should be only one.Here in MainPage I am calling Cities:
public partial class MainPage : MasterDetailPage
{ public MainPage()
{
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;
CityClick.Clicked += async (sender, e) =>
{
await Detail.Navigation.PushAsync(new Cities());
};}}
Then when I am at Cities.xaml.cs I want to back to MainPage(). And also I want pass my selected item value from list to my label in MainPage.xaml navigation. Second problem is when I am returning from Cities.xaml.cs after item select to MainPage() I am getting that error which I mentioned before. This is my Cities class:
public partial class Cities : ContentPage
{
public Cities()
{
InitializeComponent();
Label header = new Label
{
Text = ...
};
List<City> cities = new List<City>
{new City("City1"),
new City("City2")};
ListView listView = new ListView
{ItemsSource = cities,
ItemTemplate = new DataTemplate(() =>
{
Label nameLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "Name");
BoxView boxView = new BoxView();
return new ViewCell
{
...
};
...
{
Children =
{
...
}
};
listView.ItemSelected += async (sender, e) =>
{
if (e.SelectedItem == null)
{return;}
else
{
await Navigation.PushAsync(new MainPage());
}
};
}
class City
{public City(string name)
{
this.Name = name;
}
public string Name { private set; get; }
};}
And this is how looks when returns to MainPage() it freeze everything and appear another label:
EDIT : Regarding #AkashAmin comments I changed from await Navigation.PushAsync(new MainPage()); to await Navigation.PopAsync(); and it is worked very well. Now I still have dilemma with pasiing value from City class to MainPage class.
I navigated back from my Cities class to my MainPage by changing from PushAsync to PopAsync(); . Thank you #Akash Amin for your information. This awaited task also solved duplicated labels problem in Navigation ToolbarItems place .
Also I solved value passing from Cities to MainPage class problem. In this link you can see my all walkthrough of solving this problem: https://stackoverflow.com/a/37350738/3727758

How to open new TabbedPage from ContentPage?

I am trying to open (using any method) the TabbedPage from ContentPage.
My main App code:
public class App : Application
{
public App ()
{
MainPage = new ConnectPage ();
}
}
My ConnectPage uses XAML, code:
.cs file:
public partial class ConnectPage : ContentPage
{
public ConnectPage ()
{
InitializeComponent ();
}
void connectDevice(object sender, EventArgs args){
connect_btn.Text = "Connecting...";
connect_btn.IsEnabled = false;
var mainapp_page = new MainApp ();
Navigation.PushAsync (mainapp_page);
}
}
XAML file:
<Button x:Name="connect_btn" Text="Connect Now" Clicked="connectDevice"></Button>
Above method throws error:
PushAsync is not supported globally on iOS, please use a
NavigationPage
My MainApp.cs (which contain tabs):
public class MainApp : ContentPage
{
public MainApp ()
{
var tabs = new TabbedPage ();
tabs.Children.Add (new Tab1Page{Title="Tab1" });
tabs.Children.Add (new Tab2Page{Title="Tab2" });
tabs.Children.Add (new Tab3Page{Title="Tab3" });
}
}
You can either update your'r app's MainPage property and set that to the page you want to display, use stack navigation or present a page modally.
Setting a new main page will provide no way for the user to go back:
App.Current.MainPage = new SomeOtherPage ();
If you want to use stack navigation, you will have to wrap your initial page into a NavigationPage:
public partial class App : Application
{
public App ()
{
InitializeComponent ();
this.MainPage = new NavigationPage (new FirstPage ());
}
}
Than you can use Navigation.PushAsync().
If you want to present a page modally, so it is shown on top of your current page and can be dismissed, use:
Navgiation.PushModalAsync(new Page());
However, this will still require to wrap your current page into a NavigationPage.
There are other ways too, like CarouselPage or MasterDetailPage. I recommend you look at the documentation for all of your options.

Categories

Resources