Skip to content

Instantly share code, notes, and snippets.

@TheTekton
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheTekton/05ada395a8a12df57c38 to your computer and use it in GitHub Desktop.
Save TheTekton/05ada395a8a12df57c38 to your computer and use it in GitHub Desktop.
Xamarin.Forms 1.3 - TabbedPage with ContentPage ListView.SelectItem preservation when OnCurrentPageChanged
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace MyProject
{
public class MyTabbedPage : TabbedPage
{
private Type _lastPage { get; set; }
void OnCurrentPageChanged (object sender, EventArgs e)
{
if (_lastPage == typeof(Page1)) {
MessagingCenter.Send<MyTabbedPage> (this, "CurrentPageChangedFrom");
} else {
//MessagingCenter.Send<MyTabbedPage> (this, "CurrentPageChangedTo");
}
_lastPage = sender.GetType();
}
public MyTabbedPage ()
{
this.Title = "Some Editor";
this.Children.Add (new MyPage1 ());
//this.Children [0].Icon = "icons/edit24.png";
this.Children.Add (new MyPage2 ());
//this.Children [1].Icon = "icons/mobile29.png";
this.Children.Add (new MyPage3 ());
//this.Children [2].Icon = "icons/book95.png";
this.Children.Add (new MyPage4 ());
//this.Children [3].Icon = "icons/cogs3.png";
_lastPage = typeof(MyPage1);
this.CurrentPageChanged += OnCurrentPageChanged;
}
}
}
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Xamarin.Forms;
namespace MyProject
{
public class Page1 : ContentPage
{
private ListView _myListView { get; set; }
private object _scrollItem { get; set; }
public void OnPageAppearing (object sender, EventArgs e)
{
if(this._scrollItem != null) {
Foo fooScrollItem = (Foo)_scrollItem;
foreach(Foo fooItem in _myListView.ItemsSource) {
if(fooItem.Index == fooScrollItem.Index) {
_myListView.SelectedItem = fooItem;
_myListView.ScrollTo(fooItem, ScrollToPosition.Center, true);
break;
}
}
}
}
public void OnMyListViewItemSelected (object sender, SelectedItemChangedEventArgs e)
{
this._scrollItem = e.SelectedItem;
}
public Page1()
{
this.Appearing += OnPageAppearing;
MessagingCenter.Subscribe<MyTabbedPage> (this, "CurrentPageChangedFrom", (sender) => {
if(_myListView.SelectedItem != null) {
this._scrollItem = _myListView.SelectedItem;
} else {
this._scrollItem = null;
}
});
_myListView = new ListView {
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.StartAndExpand,
HasUnevenRows = true
};
_myListView.ItemSelected += OnMyListViewItemSelected;
Content = new StackLayout {
VerticalOptions = LayoutOptions.FillAndExpand,
Children = { _myListView }
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment