Xamarin forms how to keep label text value after navigation - xaml

On my Main Page, I will set my label text (#lblStartDateTime) to current time stamp when user click on a button. It will navigate to Second Page, and once I click "done" button, it will go back to Main Page.
When I navigate back to Main Page from Second Page, my label text disappeared. Does anyone know how to keep the label text value after navigation?
Main Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Test
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage: ContentPage
{
public string previouspagevalue;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
lblEndDT.Text = previouspagevalue;
}
private void btnOffline_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new SecondPage());
string currentDT = DateTime.Now.ToString();
lblStartDT.Text = currentDT;
}
}
}
Second Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Test
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SecondPage: ContentPage
{
public SecondPage()
{
InitializeComponent();
}
protected void btnDone_Clicked(object sender, EventArgs e)
{
MainPage mainpage = new MainPage();
string edt = DateTime.Now.ToString();
lblEndDateTime.Text = edt;
mainpage.previouspagevalue = lblEndDateTime.Text;
Navigation.PushAsync(mainpage);
}
}
}

In you btnDone_Clicked event , you should use Navigation.PopAsync to go back to MainPage, Navigation.PushAsync(mainpage); means to go to a new MainPage not the previous Page.
protected void btnDone_Clicked(object sender, EventArgs e)
{
Navigation.PopAsync();
}
Please read document to learn about how NavigationPage works.
Update, you can pass the value you need to the SecondPage when you push to SecondPage:
Codes in MainPage:
public partial class MainPage : ContentPage
{
public string previouspagevalue;
public MainPage()
{
InitializeComponent();
previouspagevalue = "I'm previouspagevalue";
}
protected override void OnAppearing()
{
base.OnAppearing();
//if you set the lblEndDT.Text = "someValue"; in the secondPage, there is no need to update it here
lblEndDT.Text = previouspagevalue;
}
private void btnOffline_Clicked(object sender, EventArgs e)
{
//Pass the parametere you need when you go to SecondPage
Navigation.PushAsync(new SecondPage(this, lblEndDT));
string currentDT = DateTime.Now.ToString();
lblStartDT.Text = currentDT;
}
}
SecondPage:
public partial class SecondPage : ContentPage
{
Label MainPagelblEndDT;
MainPage mainPage;
public SecondPage()
{
InitializeComponent();
}
public SecondPage(MainPage mainP,Label lblEndDT)
{
InitializeComponent();
//Get the lblEndDT reference here
MainPagelblEndDT = lblEndDT;
//Get the MainPage reference here
mainPage = mainP;
}
private void Button_Clicked(object sender, EventArgs e)
{
string edt = DateTime.Now.ToString();
//Use it
MainPagelblEndDT.Text = edt;
mainPage.previouspagevalue = MainPagelblEndDT.Text;
Navigation.PopAsync();
}
}
I uploaded a sample project here and you can check it. Feel free to ask me any question if you have.

I would suggest you wrap your pages in a navigation stack, use a NavigationPage and navigate to next page then when you pop back it will maintain your state.
In your App.xaml.cs
MainPage = new NavigationPage(new YourFirstPage);
Then push a page into the navigation and when you want to go back just do a
Navigation.PopAsync();
Goodluck
Feel free to get back if you have queries

Related

Emulator show empty white screen problem on Xamarin Forms

I was testing what I done with android emulator and it always worked well but yesterday it suddenly shows my app as a just white blank screen. I dont know the reason why.
This my MainActivity class
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
namespace HealthCareApp.Droid
{
[Activity(Label = "HealthCareApp", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Forms.SetFlags("Brush_Experimental");
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new Xamarin.Forms.Application());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
App.xaml.cs ( now its giving a error : "initializecomponent is inaccessible due to its protection level" )
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace HealthCareApp
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new LoginPage());
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
You should have a App class somewhere in your project, which contains information of which Forms page to show first and setup stuff like services in a IoC container etc.
Instead of calling
LoadApplication(new Xamarin.Forms.Application());
You should probably call:
LoadApplication(new App());

PRISM Xamarin - Working with tabbed pages (IActiveAware)

I have tab pages implementing different views, but I cannot initialize each of the tabs when navigating.
<TabbedPage.Children>
<tabPages:Page1/>
<tabPages:Page2/>
<tabPages:Page3/>
</TabbedPage.Children>
So what I did was to use IActiveAware as prism documentation suggested to know which tab page is currently active. So I have this class:
public abstract class TabbedChildViewModelBase : BaseViewModel, IActiveAware, INavigationAware, IDestructible
protected bool IsInitalized { get; set; }
private bool _IsActive;
public bool IsActive
{
get
{
return _IsActive;
}
set
{
SetProperty(ref _IsActive, value, RaiseIsActiveChanged);
}
}
public event EventHandler IsActiveChanged;
public virtual void OnNavigatingTo(NavigationParameters parameters)
{
}
protected virtual void RaiseIsActiveChanged()
{
IsActiveChanged?.Invoke(this, EventArgs.Empty);
}
public virtual void Destroy()
{
}
}
So each child view models inherits the child view model base:
public class Page1 : TabbedChildViewModelBase
{
public CurrentSeaServiceViewModel()
{
IsActiveChanged += HandleIsActiveTrue;
IsActiveChanged += HandleIsActiveFalse;
}
private void HandleIsActiveTrue(object sender, EventArgs args)
{
if (IsActive == false)
{
TestLabelOnly = "Test";
}
// Handle Logic Here
}
private void HandleIsActiveFalse(object sender, EventArgs args)
{
if (IsActive == true) return;
// Handle Logic Here
}
public override void Destroy()
{
IsActiveChanged -= HandleIsActiveTrue;
IsActiveChanged -= HandleIsActiveFalse;
}
}
The problem is, the child vm isn't initializing. Is there something needed in order to implement IActiveAware properly nor launching the IsActive property
I still used IActiveAware unfortunately, to make the childtabbedviewmodel work you need to bind the page to its own view model.
So here's what I did:
<TabbedPage.Children>
<views:ChildPage1>
<views:ChildPage1.BindingContext>
<viewModels:ChildPage1ViewModel/>
</views:ChildPage1.BindingContext>
</views:ChildPage1>
<views:ChildPage2>
<views:ChildPage2.BindingContext>
<viewModels:ChildPage2ViewModel/>
</views:ChildPage2.BindingContext>
</views:ChildPage2>
</TabbedPage.Children>
I used the property BindingContext of my views and
using IActiveAware I would also know what tab is currently active. Hope anyone helps this who finds trouble binding the child pages of a tab.

How to make toolbar item in Carousel page go to other page

I have a carousel page and a home icon in the toolbar. When clicking the home icon, error appears.
Code in Xaml
<ContentPage.ToolbarItems>
<ToolbarItem Icon="home.png" Command="{Binding HomeCommand}"/>
</ContentPage.ToolbarItems>
Code in ViewModel
public class InfoItemViewModel : ObservableObject, INavigatedAware
{
public DelegateCommand HomeCommand { get; private set; }
private INavigationService mNavigationService;
public INavigationService navigationService;
public InfoItemViewModel(int productId, INavigationService navigationService)
: base(listenCultureChanges: true)
{
_productId = productId;
mNavigationService = navigationService;
HomeCommand = new DelegateCommand(HomeAction);
LoadData();
}
private async void HomeAction()
{
Debug.WriteLine("Button : Home");
await mNavigationService.NavigateAsync("DashboardMenuPage");
}
Code in Xaml.cs
public partial class InfoItem : ContentPage
{
public InfoItem()
: **this**(DataMyDOF.Products[0].Id)
{
}
public InfoItem(int productId, INavigationService navigationService)
{
InitializeComponent();
BindingContext = new InfoItemViewModel(productId, navigationService);
}
}
}
The error 'this'
There is no argument given that corresponds to the required formal
parameter ‘navigationService’ of ‘InfoItem.InfoItem(int,
INavigationService)’
After i add navigationService in the constructor, 'this' appears error. Actually I combine the carousel code from grial with prism. Products[0].Id is the array id. Should i add the navigation as the parameter too?
I tried to use Xamarin Forms Navigation. But still there's an error.
using Xamarin.Forms;
public INavigation Navigation { get; }
private void HomeAction()
{
Debug.WriteLine("Button : Home");
Navigation.PushAsync(new NavigationPage(new DashboardMenuPage()));
}
The error
System.NullReferenceException has been thrown Object reference not set
to an instance of an object

Xamarin MVVM push user data to viewmodel

like the title says I want to give through the user information to my viewmodel, but the problem is that the viewmodel is registered as a dependency and I am binding its content to the xaml page itself. How do I send the user information to the viewmodel itself?
Thank you!
Xaml.cs part:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Calendar : ContentPage
{
public Calendar(User user)
{
InitializeComponent();
FileImageSource image = new FileImageSource
{
File = "calendar.png"
};
Icon = image;// push user information to the ICalendarViewModel
BindingContext = AppContainer.Container.Resolve<ICalendarViewModel>();
}
}
Interface:
public interface ICalendarViewModel : INotifyPropertyChanged
{
}
Bootstrap part registering dependencies:
public class Bootstrap
{
public IContainer CreateContainer()
{
var containerBuilder = new ContainerBuilder();
RegisterDependencies(containerBuilder);
return containerBuilder.Build();
}
protected virtual void RegisterDependencies(ContainerBuilder builder)
{
builder.RegisterType<CalendarViewModel>()
.As<ICalendarViewModel>()
.SingleInstance();
}
}
CalendarViewModel: I do not know if this will help
public class CalendarViewModel : ViewModelBase, ICalendarViewModel
{
public event PropertyChangedEventHandler PropertyChanged;
public string ErrorMessage { get; set; }
private CourseInformation _information;
private ICourseInformationRepository _repository;
public CalendarViewModel()
{
_repository = new CourseInformationRepository();
LoadData();
}
private ObservableCollection<CourseInformation> _courses;
public ObservableCollection<CourseInformation> Courses
{
get
{
return _courses;
}
set
{
_courses = value;
RaisePropertyChanged(nameof(Courses));
}
}
private void LoadData()
{
try
{
ObservableCollection<CourseInformation> CourseList = new ObservableCollection<CourseInformation>(_repository.GetAllCourseInformation());
Courses = new ObservableCollection<CourseInformation>();
DateTime date;
foreach (var course in CourseList)
{
string [] cour = course.Date.Split('/');
cour[2] = "20" + cour[2];
date = new DateTime(Convert.ToInt32(cour[2]), Convert.ToInt32(cour[1]), Convert.ToInt32(cour[0]));
if (date == DateTime.Now)//TESTING WITH TEST DATE, datetime.now
{
if (course.FromTime.Length < 4)
{
course.FromTime = "0" + course.FromTime;
}
if (course.UntilTime.Length < 4)
{
course.UntilTime = "0" + course.UntilTime;
}
course.FromTime = course.FromTime.Insert(2, ":");
course.UntilTime = course.UntilTime.Insert(2, ":");
Courses.Add(course);
}
}
}
catch (ServerUnavailableException e)
{
ErrorMessage = "Server is niet beschikbaar, ophalen van kalender is niet mogelijk.";
}
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Bootstrap binding in app.xaml.cs:
public partial class App : Application
{
public App()
{
InitializeComponent();
AppContainer.Container = new Bootstrap().CreateContainer();
MainPage = new LoginView();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
I wanted to comment (not enough reputation) on #LeRoy, use a framework. I would recommend FreshMVVM and you can pass objects into the ViewModel and even pass in Services. It makes it all nice and clean, and it just works.
Should not your CalendarViewModel viewModel contain BindableBase ?
public class CalendarViewModel : BindableBase, ViewModelBase, ICalendarViewModel
what framework are you using? prism, freshmvvm.
Your View and Viewmodel is normally automatically handled by the framework, all you need to do is register your page.
Container.RegisterTypeForNavigation<Views.CalendarPage>();

Why should we actually use Dependency Properties?

This code doesn't work :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightPlainWCF.CustomersServiceRef;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace SilverlightPlainWCF
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.DataContext = Customers;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
public static readonly string CustomersPropertyName = "Customers";
// public DependencyProperty CustomersProperty = DependencyProperty.Register(CustomersPropertyName,typeof(ObservableCollection<Customer>)
// ,typeof(MainPage),new PropertyMetadata(null));
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
//get { return GetValue(CustomersProperty) as ObservableCollection<Customer>; }
//set
//{
// SetValue(CustomersProperty, value);
//}
get
{
return customers;
}
set
{
customers = value;
}
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
CustomersServiceClient objCustomersServiceClient = new CustomersServiceClient();
objCustomersServiceClient.GetAllCustomersCompleted += (s, res) =>
{
if (res.Error == null)
{
Customers = res.Result;
}
else
{
MessageBox.Show(res.Error.Message);
}
};
objCustomersServiceClient.GetAllCustomersAsync();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
// Do not load your data at design time.
// if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
// {
// //Load your data here and assign the result to the CollectionViewSource.
// System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
// myCollectionViewSource.Source = your data
// }
// Do not load your data at design time.
// if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
// {
// //Load your data here and assign the result to the CollectionViewSource.
// System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
// myCollectionViewSource.Source = your data
// }
}
private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
{
}
private void customerDataGrid_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
{
var Customer = Customers[e.Row.GetIndex()];
Debug.WriteLine(Customer);
}
private void customerDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
Whereas if i just change the above property of Customers to this :-
public static readonly string CustomersPropertyName = "Customers";
public DependencyProperty CustomersProperty = DependencyProperty.Register(CustomersPropertyName,typeof(ObservableCollection<Customer>)
,typeof(MainPage),new PropertyMetadata(null));
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
get { return GetValue(CustomersProperty) as ObservableCollection<Customer>; }
set
{
SetValue(CustomersProperty, value);
}
}
it works. Why is it that only with DependencyProperty the grid gets populated? Please explain me in little detail. Also, do i have to compulsorily use ObservableCollection or even List is fine?
Short answer: Dependency properties are wrappers which know how to 'dispatch changes'.
See Dependency Properties Overview