Xamarin Forms : Add ItemSource on focus - xamarin

Am trying to load ItemSource of a picker when the picker is focused.
But the data is not loaded on 1st focus.
here is the code sample
List<object> itmSrc;
Picker picker = new Picker();
itmSrc = Controls[i].ItemSource;
picker.Focused += BindItemSourceOnFocus;
public void BindItemSourceOnFocus(object sender, FocusEventArgs e)
{
var p = e.VisualElement as Picker;
p.ItemsSource = itmSrc;
}
If any other different approach is possible, let me know.

You can do it adding items on an async method, or another thread. Load the data on view focus is just transferring the issue to another place, and it gives a bad user experience at all.
If you run a code block inside a Task.Run(), for example, this code will be executed on another thread, and the interface should not hang on data loading.
Something like this:
public class MyPage : ContentPage
{
List<object> itmSrc;
Picker picker;
public MyPage()
{
// Your stuff goes here
itmSrc = new List<object>();
picker = new Picker();
StackLayout content = new StackLayout();
content.Crindren.Add(picker);
this.Content = content;
Task.Run(() => LoadData());
}
private void LoadData()
{
// Get your data from anywhere and put it on the itemSrc from here.
// Then...
picker.ItemsSource = itmSrc;
}
}
I hope it helps.

Related

WPF Using of Frame

While I'm using frame in Mainwindow , initially i hide an item in Mainwindows.
When i pressed a button in frame Page1 , I want to make item in mainwindow as visible.But i can't do it.I tried to updatelayout() , refresh() functions but anything is changed.Anyone has a knowledge about this??
This code is in MainWindow
private void Window_Loaded(object sender, RoutedEventArgs e)
{
müsteributton.IsEnabled = false;
string yer = "Pages/kullanicigiris.xaml";
frame1.Source = new Uri(yer, UriKind.Relative);
frame1.Margin = new Thickness(-175, 0, 0, 0);
}
This code is in kullanicigiris page
private void Dispatcher_Tick(object sender, EventArgs e)
{
i++;
if (i == 2)
{
dispatcher.Stop();
frm1 = new MainWindow();
frm1.frame1 = null;
DependencyObject currParent = VisualTreeHelper.GetParent(this);
while (currParent != null && frm1.frame1 == null)
{
frm1.frame1 = currParent as Frame;
currParent = VisualTreeHelper.GetParent(currParent);
}
// Change the page of the frame.
if (frm1.frame1 != null)
{
frm1.frame1.Source = new Uri("Window1.xaml", UriKind.Relative);
frm1.müsteributton.IsEnabled = true;
}
}
}
Thanks.
You can define a DependencyProperty in the MainWindows.
<TextBlock x:Name="textBlock" Height="399" TextWrapping="Wrap" Text="Show/ Hide" VerticalAlignment="Top" Visibility="{Binding SetVisibility, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
public static readonly DependencyProperty SetVisibilityProperty =
DependencyProperty.Register("SetVisibility", typeof(Visibility), typeof(Mainfreampage), new
PropertyMetadata(Visibility.Visible, null));
public Visibility SetVisibility
{
get { return (Visibility)GetValue(SetVisibilityProperty); }
set { SetValue(SetVisibilityProperty, value); }
}
In your page click event, you can use the following code find the MainWindows and change the DependencyProperty value.
var mw = Application.Current.Windows
.Cast<Mainfreampage>()
.FirstOrDefault(window => window is Mainfreampage) as Mainfreampage;
mw.SetVisibility = Visibility.Hidden;
Your bug is here:
frm1 = new MainWindow();
You are creating a brand new window, and then making your changes in that window.
But: that's not the window the user's looking at!
Taking the approach you've embarked on, your frame code needs to keep track of the Window object it's actually being hosted in, and then use that reference for dealing with the update.
That said, that entire approach is flawed. The navigation should be modeled in a view model data structure, activated via an ICommand object, and optionally via timer (as you seem to be doing here). Frame source and button state can be manipulated through bindings to properties in your view model data structure.
But, at the end of the day, the code you've got should work fine, once you start using the correct Window object.

Multiple alerts with only one MessagingCenter subscription

I'm developing a sample where Messaging Center send status messeges not coupled from device code to my view models. At this point i used a alert message to notice the event before try in View models.
For it I used a static view instance in my share application constructor (App.xaml) where in view constructor I Subscript the status.
App (shared)
public partial class App : Application
{
#region MasterDetailPage
public static MasterDetailPage MDP;
public static NavigationPage NAV = null;
public static MainView _mainpage;
#endregion
public App ()
{
InitializeComponent();
NAV = new NavigationPage(new StarterView()) { BarBackgroundColor = Color.FromHex("701424"), BarTextColor = Color.White }; ;
MDP = new MasterDetailPage();
MDP.BackgroundColor = Xamarin.Forms.Color.FromHex("701424");
_mainpage = new MainView();
MDP.Master = _mainpage;
MDP.Detail = NAV;
MainPage = MDP;
MainPage.Title = "H2X";
}
(View shared)
public MainView ()
{
InitializeComponent ();
string a="Test";
#region MessegeCenter
MessagingCenter.Subscribe<string,string>("APP", "Message_Received", async (sender,arg) =>
{
string b = a;
a = $"{arg}";
await DisplayAlert("Atenção", a+b, "Ok");
});
#endregion
}
Into the specific platform code (Device - UWP) I create a timer that sends messages after some time instanced in mainpage constructor.
void dispatcherTimer_Tick(object sender, object e)
{
DateTimeOffset time = DateTimeOffset.Now;
TimeSpan span = time - lastTime;
lastTime = time;
//Time since last tick should be very very close to Interval
TimerLog.Text += timesTicked + "\t time since last tick: " + span.ToString() + "\n";
timesTicked++;
if (timesTicked > timesToTick)
{
MessagingCenter.Send<string,string>("APP","Message_Received","MR");
}
}
When I run it, twice alert messages with the same text are opening, but there aren't two subscriptions. The same text give me the information that it was from the same send event.
Where is the problem ? Is there any relationship with my static view ?
Thank you in advance
Guilherme
It is a good practice to always unsubscribe from the MessagingCenter.
MessagingCenter.Unsubscribe<string, string>(this, "Message_Received");
If MessagingCenter is subscribed twice ,then functions will be call twice.

Create ContentPage template with fixed view on top

Our Xamarin.Forms app works online and offline by downloading an original database to the cell phone and then syncing the SQLite database with the online database.
Our users need a way to see if they are online and if the changes they made got uploaded to the online database. What I try to achieve is to show the sync status at the top of every ContentPage, so the users can see this information all the time while working with the app.
What I tried is this: create a class "SyncInfoContentPage" that inherits from ContentPage. All ContentPages I already wrote will now not inherit from ContentPage anymore but from SyncInfoContentPage.
The SyncInfoContentPage automatically takes its Content and replaces it with a new Stacklayout that includes the SyncInfo and the original content. By doing this I don't have to rewrite the 77 ContentPages we already have.
This code works fine on Android, but on iOS the SyncInfo is not visible and (even worse) my ContentPages that inherit from SyncInfoContentPage do not react to anything anymore.
Here is my code:
public class SyncInfoContentPage : ContentPage
{
private readonly Frame SyncInfo;
public SyncInfoContentPage()
{
SyncInfo = BuildSyncInfo(); //Creates the frame with the sync Information
PropertyChanged += SyncInfoContentPage_PropertyChanged;
}
private void SyncInfoContentPage_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// Add the SyncInfo Frame on top of the Content when the Content gets changed
if (e.PropertyName.Equals("Content"))
{
bool change = false;
// If the content already is a StackLayout, check if the SyncInfo already got added, so that theres no infinite loop.
if (Content is StackLayout)
{
var check = Content as StackLayout;
if (!check.Children.Contains(SyncInfo))
{
change = true;
}
}
else // if the Content is no StackLayout, the SyncInfo Frame can't be inside the Content yet
{
change = true;
}
if (change)
{
var layout = Content; // This is a reference, probably the error?
Device.BeginInvokeOnMainThread(() =>
{
Content = new StackLayout
{
Children = { SyncInfo, layout }
};
});
}
}
}
}
The problem is probably that iOS doesn't like this part:
var layout = Content;
Content = new StackLayout { Children = { SyncInfo, layout } };
Thanks in advance for your help and any suggestions :-)
I got it to work. The solution is simple but strange. You have to add the original Content after you added the SyncInfo status bar.
var layoutOld = Content;
var layoutNew = new StackLayout
{
Children = { SyncInfo }
};
Content = layoutNew;
layoutNeu.Children.Add(layoutOld);

RecyclerView Click event

I have created a RecyclerView adapter and I'm trying to start an activity when a row is clicked:
public override OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
MyViewHolder viewHolder = (MyViewHolder)holder;
viewHolder.MyView.Click += (sender, e) =>
{
var context = viewHolder.MyView.Context;
var intent = new Intent(context, typeof(DetailActivity));
context.StartActivity(intent);
}
}
When I click the first row it will take me to the activity like I want. If I scroll down so that the first row is rebound and then scroll back to the top again and then click the first row then my Click event fires twice. Once for the first row that was bound and then again for a row that was bound when I scrolled.
Is there an event you need to handle to unregister the click events?
I believe the standard pattern is to setup your clickhandlers in the constructor of the ViewHolder. Then in OnBindViewHolder, you update the Views/Data inside the ViewHolder.
Something like this (not compiled code):
Adapter:
public override OnBindViewHolder()
{
MyViewHolder viewHolder = (MyViewHolder)holder;
viewHolder.SetData(whatever data you care about);
}
MyViewHolder:
public MyViewHolder(View view) : base(view)
{
MainView = view;
MainView.Click += (sender, e) =>
{
var context = MainView.Context;
var intent = new Intent(context, typeof(DetailActivity));
context.StartActivity(intent);
}
}
Doing it this way keeps the Adapter cleaner by putting business logic in the ViewHolder, and also prevents your click handlers from being constantly setup and torn down as you scroll.

How do you switch pages in Xamarin.Forms?

How do you switch between pages in Xamarin Forms?
My main page is a ContentPage and I don't want to switch to something like a Tabbed Page.
I've been able to pseudo-do it by finding parents of the controls that should trigger the new page until I find the ContentPage and then swap out the Content with controls for a new page. But this seems really sloppy.
In the App class you can set the MainPage to a Navigation Page and set the root page to your ContentPage:
public App ()
{
// The root page of your application
MainPage = new NavigationPage( new FirstContentPage() );
}
Then in your first ContentPage call:
Navigation.PushAsync (new SecondContentPage ());
Xamarin.Forms supports multiple navigation hosts built-in:
NavigationPage, where the next page slide in,
TabbedPage, the one you don't like
CarouselPage, that allows for switching left and right to next/prev pages.
On top of this, all pages also supports PushModalAsync() which just push a new page on top of the existing one.
At the very end, if you want to make sure the user can't get back to the previous page (using a gesture or the back hardware button), you can keep the same Page displayed and replace its Content.
The suggested options of replacing the root page works as well, but you'll have to handle that differently for each platform.
If your project has been set up as a PCL forms project (and very likely as Shared Forms as well but I haven't tried that) there is a class App.cs that looks like this:
public class App
{
public static Page GetMainPage ()
{
AuditorDB.Model.Extensions.AutoTimestamp = true;
return new NavigationPage (new LoginPage ());
}
}
you can modify the GetMainPage method to return a new TabbedPaged or some other page you have defined in the project
From there on you can add commands or event handlers to execute code and do
// to show OtherPage and be able to go back
Navigation.PushAsync(new OtherPage());
// to show AnotherPage and not have a Back button
Navigation.PushModalAsync(new AnotherPage());
// to go back one step on the navigation stack
Navigation.PopAsync();
Push a new page onto the stack, then remove the current page. This results in a switch.
item.Tapped += async (sender, e) => {
await Navigation.PushAsync (new SecondPage ());
Navigation.RemovePage(this);
};
You need to be in a Navigation Page first:
MainPage = NavigationPage(new FirstPage());
Switching content isn't ideal as you have just one big page and one set of page events like OnAppearing ect.
If you do not want to go the previous page i.e. do not let the user go back to the login screen once authorization is done, then you can use;
App.Current.MainPage = new HomePage();
If you want to enable back functionality, just use
Navigation.PushModalAsync(new HomePage())
Seems like this thread is very popular and it will be sad not to mention here that there is an alternative way - ViewModel First Navigation. Most of the MVVM frameworks out there using it, however if you want to understand what it is about, continue reading.
All the official Xamarin.Forms documentation is demonstrating a simple, yet slightly not MVVM pure solution. That is because the Page(View) should know nothing about the ViewModel and vice versa. Here is a great example of this violation:
// C# version
public partial class MyPage : ContentPage
{
public MyPage()
{
InitializeComponent();
// Violation
this.BindingContext = new MyViewModel();
}
}
// XAML version
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodels="clr-namespace:MyApp.ViewModel"
x:Class="MyApp.Views.MyPage">
<ContentPage.BindingContext>
<!-- Violation -->
<viewmodels:MyViewModel />
</ContentPage.BindingContext>
</ContentPage>
If you have a 2 pages application this approach might be good for you. However if you are working on a big enterprise solution you better go with a ViewModel First Navigation approach. It is slightly more complicated but much cleaner approach that allow you to navigate between ViewModels instead of navigation between Pages(Views). One of the advantages beside clear separation of concerns is that you could easily pass parameters to the next ViewModel or execute an async initialization code right after navigation. Now to details.
(I will try to simplify all the code examples as much as possible).
1. First of all we need a place where we could register all our objects and optionally define their lifetime. For this matter we can use an IOC container, you can choose one yourself. In this example I will use Autofac(it is one of the fastest available). We can keep a reference to it in the App so it will be available globally (not a good idea, but needed for simplification):
public class DependencyResolver
{
static IContainer container;
public DependencyResolver(params Module[] modules)
{
var builder = new ContainerBuilder();
if (modules != null)
foreach (var module in modules)
builder.RegisterModule(module);
container = builder.Build();
}
public T Resolve<T>() => container.Resolve<T>();
public object Resolve(Type type) => container.Resolve(type);
}
public partial class App : Application
{
public DependencyResolver DependencyResolver { get; }
// Pass here platform specific dependencies
public App(Module platformIocModule)
{
InitializeComponent();
DependencyResolver = new DependencyResolver(platformIocModule, new IocModule());
MainPage = new WelcomeView();
}
/* The rest of the code ... */
}
2.We will need an object responsible for retrieving a Page (View) for a specific ViewModel and vice versa. The second case might be useful in case of setting the root/main page of the app. For that we should agree on a simple convention that all the ViewModels should be in ViewModels directory and Pages(Views) should be in the Views directory. In other words ViewModels should live in [MyApp].ViewModels namespace and Pages(Views) in [MyApp].Views namespace. In addition to that we should agree that WelcomeView(Page) should have a WelcomeViewModel and etc. Here is a code example of a mapper:
public class TypeMapperService
{
public Type MapViewModelToView(Type viewModelType)
{
var viewName = viewModelType.FullName.Replace("Model", string.Empty);
var viewAssemblyName = GetTypeAssemblyName(viewModelType);
var viewTypeName = GenerateTypeName("{0}, {1}", viewName, viewAssemblyName);
return Type.GetType(viewTypeName);
}
public Type MapViewToViewModel(Type viewType)
{
var viewModelName = viewType.FullName.Replace(".Views.", ".ViewModels.");
var viewModelAssemblyName = GetTypeAssemblyName(viewType);
var viewTypeModelName = GenerateTypeName("{0}Model, {1}", viewModelName, viewModelAssemblyName);
return Type.GetType(viewTypeModelName);
}
string GetTypeAssemblyName(Type type) => type.GetTypeInfo().Assembly.FullName;
string GenerateTypeName(string format, string typeName, string assemblyName) =>
string.Format(CultureInfo.InvariantCulture, format, typeName, assemblyName);
}
3.For the case of setting a root page we will need sort of ViewModelLocator that will set the BindingContext automatically:
public static class ViewModelLocator
{
public static readonly BindableProperty AutoWireViewModelProperty =
BindableProperty.CreateAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), default(bool), propertyChanged: OnAutoWireViewModelChanged);
public static bool GetAutoWireViewModel(BindableObject bindable) =>
(bool)bindable.GetValue(AutoWireViewModelProperty);
public static void SetAutoWireViewModel(BindableObject bindable, bool value) =>
bindable.SetValue(AutoWireViewModelProperty, value);
static ITypeMapperService mapper = (Application.Current as App).DependencyResolver.Resolve<ITypeMapperService>();
static void OnAutoWireViewModelChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as Element;
var viewType = view.GetType();
var viewModelType = mapper.MapViewToViewModel(viewType);
var viewModel = (Application.Current as App).DependencyResolver.Resolve(viewModelType);
view.BindingContext = viewModel;
}
}
// Usage example
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodels="clr-namespace:MyApp.ViewModel"
viewmodels:ViewModelLocator.AutoWireViewModel="true"
x:Class="MyApp.Views.MyPage">
</ContentPage>
4.Finally we will need a NavigationService that will support ViewModel First Navigation approach:
public class NavigationService
{
TypeMapperService mapperService { get; }
public NavigationService(TypeMapperService mapperService)
{
this.mapperService = mapperService;
}
protected Page CreatePage(Type viewModelType)
{
Type pageType = mapperService.MapViewModelToView(viewModelType);
if (pageType == null)
{
throw new Exception($"Cannot locate page type for {viewModelType}");
}
return Activator.CreateInstance(pageType) as Page;
}
protected Page GetCurrentPage()
{
var mainPage = Application.Current.MainPage;
if (mainPage is MasterDetailPage)
{
return ((MasterDetailPage)mainPage).Detail;
}
// TabbedPage : MultiPage<Page>
// CarouselPage : MultiPage<ContentPage>
if (mainPage is TabbedPage || mainPage is CarouselPage)
{
return ((MultiPage<Page>)mainPage).CurrentPage;
}
return mainPage;
}
public Task PushAsync(Page page, bool animated = true)
{
var navigationPage = Application.Current.MainPage as NavigationPage;
return navigationPage.PushAsync(page, animated);
}
public Task PopAsync(bool animated = true)
{
var mainPage = Application.Current.MainPage as NavigationPage;
return mainPage.Navigation.PopAsync(animated);
}
public Task PushModalAsync<TViewModel>(object parameter = null, bool animated = true) where TViewModel : BaseViewModel =>
InternalPushModalAsync(typeof(TViewModel), animated, parameter);
public Task PopModalAsync(bool animated = true)
{
var mainPage = GetCurrentPage();
if (mainPage != null)
return mainPage.Navigation.PopModalAsync(animated);
throw new Exception("Current page is null.");
}
async Task InternalPushModalAsync(Type viewModelType, bool animated, object parameter)
{
var page = CreatePage(viewModelType);
var currentNavigationPage = GetCurrentPage();
if (currentNavigationPage != null)
{
await currentNavigationPage.Navigation.PushModalAsync(page, animated);
}
else
{
throw new Exception("Current page is null.");
}
await (page.BindingContext as BaseViewModel).InitializeAsync(parameter);
}
}
As you may see there is a BaseViewModel - abstract base class for all the ViewModels where you can define methods like InitializeAsync that will get executed right after the navigation. And here is an example of navigation:
public class WelcomeViewModel : BaseViewModel
{
public ICommand NewGameCmd { get; }
public ICommand TopScoreCmd { get; }
public ICommand AboutCmd { get; }
public WelcomeViewModel(INavigationService navigation) : base(navigation)
{
NewGameCmd = new Command(async () => await Navigation.PushModalAsync<GameViewModel>());
TopScoreCmd = new Command(async () => await navigation.PushModalAsync<TopScoreViewModel>());
AboutCmd = new Command(async () => await navigation.PushModalAsync<AboutViewModel>());
}
}
As you understand this approach is more complicated, harder to debug and might be confusing. However there are many advantages plus you actually don't have to implement it yourself since most of the MVVM frameworks support it out of the box. The code example that is demonstrated here is available on github. There are plenty of good articles about ViewModel First Navigation approach and there is a free Enterprise Application Patterns using Xamarin.Forms eBook which is explaining this and many other interesting topics in detail.
By using the PushAsync() method you can push and PopModalAsync() you can pop pages to and from the navigation stack. In my code example below I have a Navigation page (Root Page) and from this page I push a content page that is a login page once I am complete with my login page I pop back to the root page
~~~ Navigation can be thought of as a last-in, first-out stack of Page objects.To move from one page to another an application will push a new page onto this stack. To return back to the previous page the application will pop the current page from the stack. This navigation in Xamarin.Forms is handled by the INavigation interface
Xamarin.Forms has a NavigationPage class that implements this interface and will manage the stack of Pages. The NavigationPage class will also add a navigation bar to the top of the screen that displays a title and will also have a platform appropriate Back button that will return to the previous page. The following code shows how to wrap a NavigationPage around the first page in an application:
Reference to content listed above and a link you should review for more information on Xamarin Forms, see the Navigation section:
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/introduction-to-xamarin-forms/
~~~
public class MainActivity : AndroidActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
// Set our view from the "main" layout resource
SetPage(BuildView());
}
static Page BuildView()
{
var mainNav = new NavigationPage(new RootPage());
return mainNav;
}
}
public class RootPage : ContentPage
{
async void ShowLoginDialog()
{
var page = new LoginPage();
await Navigation.PushModalAsync(page);
}
}
//Removed code for simplicity only the pop is displayed
private async void AuthenticationResult(bool isValid)
{
await navigation.PopModalAsync();
}
In App.Xaml.Cs:
MainPage = new NavigationPage( new YourPage());
When you wish to navigate from YourPage to the next page you do:
await Navigation.PushAsync(new YourSecondPage());
You can read more about Xamarin Forms navigation here: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/hierarchical
Microsoft has quite good docs on this.
There is also the newer concept of the Shell. It allows for a new way of structuring your application and simplifies navigation in some cases.
Intro: https://devblogs.microsoft.com/xamarin/shell-xamarin-forms-4-0-getting-started/
Video on basics of Shell: https://www.youtube.com/watch?v=0y1bUAcOjZY&t=3112s
Docs: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/
Call:
((App)App.Current).ChangeScreen(new Map());
Create this method inside App.xaml.cs:
public void ChangeScreen(Page page)
{
MainPage = page;
}
In Xamarin we have page called NavigationPage. It holds stack of ContentPages.
NavigationPage has method like PushAsync() and PopAsync(). PushAsync add a page at the top of the stack, at that time that page will become the currently active page. PopAsync() method remove the page from the top of the stack.
In App.Xaml.Cs set like.
MainPage = new NavigationPage( new YourPage());
From YourPage you await Navigation.PushAsync(new newPage()); this method will add newPage at the top of the stack. At this time newPage will be currently active page.
One page to another page navigation in Xamarin.forms using Navigation property Below sample code
void addClicked(object sender, EventArgs e)
{
//var createEmp = (Employee)BindingContext;
Employee emp = new Employee();
emp.Address = AddressEntry.Text;
App.Database.SaveItem(emp);
this.Navigation.PushAsync(new EmployeeDetails());
this.Navigation.PushModalAsync(new EmployeeDetails());
}
To navigate one page to another page with in view cell Below code Xamrian.forms
private async void BtnEdit_Clicked1(object sender, EventArgs e)
{
App.Database.GetItem(empid);
await App.Current.MainPage.Navigation.PushModalAsync(new EmployeeRegistration(empid));
}
Example like below
public class OptionsViewCell : ViewCell
{
int empid;
Button btnEdit;
public OptionsViewCell()
{
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
if (this.BindingContext == null)
return;
dynamic obj = BindingContext;
empid = Convert.ToInt32(obj.Eid);
var lblname = new Label
{
BackgroundColor = Color.Lime,
Text = obj.Ename,
};
var lblAddress = new Label
{
BackgroundColor = Color.Yellow,
Text = obj.Address,
};
var lblphonenumber = new Label
{
BackgroundColor = Color.Pink,
Text = obj.phonenumber,
};
var lblemail = new Label
{
BackgroundColor = Color.Purple,
Text = obj.email,
};
var lbleid = new Label
{
BackgroundColor = Color.Silver,
Text = (empid).ToString(),
};
//var lbleid = new Label
//{
// BackgroundColor = Color.Silver,
// // HorizontalOptions = LayoutOptions.CenterAndExpand
//};
//lbleid.SetBinding(Label.TextProperty, "Eid");
Button btnDelete = new Button
{
BackgroundColor = Color.Gray,
Text = "Delete",
//WidthRequest = 15,
//HeightRequest = 20,
TextColor = Color.Red,
HorizontalOptions = LayoutOptions.EndAndExpand,
};
btnDelete.Clicked += BtnDelete_Clicked;
//btnDelete.PropertyChanged += BtnDelete_PropertyChanged;
btnEdit = new Button
{
BackgroundColor = Color.Gray,
Text = "Edit",
TextColor = Color.Green,
};
// lbleid.SetBinding(Label.TextProperty, "Eid");
btnEdit.Clicked += BtnEdit_Clicked1; ;
//btnEdit.Clicked += async (s, e) =>{
// await App.Current.MainPage.Navigation.PushModalAsync(new EmployeeRegistration());
//};
View = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White,
Children = { lbleid, lblname, lblAddress, lblemail, lblphonenumber, btnDelete, btnEdit },
};
}
private async void BtnEdit_Clicked1(object sender, EventArgs e)
{
App.Database.GetItem(empid);
await App.Current.MainPage.Navigation.PushModalAsync(new EmployeeRegistration(empid));
}
private void BtnDelete_Clicked(object sender, EventArgs e)
{
// var eid = Convert.ToInt32(empid);
// var item = (Xamarin.Forms.Button)sender;
int eid = empid;
App.Database.DeleteItem(empid);
}
}
After PushAsync use PopAsync (with this) to remove current page.
await Navigation.PushAsync(new YourSecondPage());
this.Navigation.PopAsync(this);
XAML page add this
<ContentPage.ToolbarItems>
<ToolbarItem Text="Next" Order="Primary"
Activated="Handle_Activated"/>
</ContentPage.ToolbarItems>
on the CS page
async void Handle_Activated(object sender, System.EventArgs e)
{
await App.Navigator.PushAsync(new PAGE());
}

Resources