How can I make my navigation bar text bold? - xamarin.forms

I have a Master-Detail architecture, and I need to make the detail page's title text of the navigation bar bold. How can I do that the simplest way?
Here is some of my code:
private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MainMDPageMenuItem;
if (item == null)
return;
item.ItemBorderColor = Color.Red; // Make a red frame around the selected item
if (PreviouslySelectedItem != null)
{
PreviouslySelectedItem.ItemBorderColor = Color.FromHex("#00a8d5"); // Return the original color to the previously selected (now deselected) item
}
var page = (Page)Activator.CreateInstance(item.TargetType);
page.Title = item.Title; // THIS IS THE TITLE I AM TALKING ABOUT
Detail = new NavigationPage(page);
IsPresented = false;
MasterPage.ListView.SelectedItem = null;
PreviouslySelectedItem = item;
}

I was given a solution here:
https://forums.xamarin.com/discussion/comment/358994#Comment_358994
It is done by using TitleView:
var page = (Page)Activator.CreateInstance(item.TargetType);
var titleView = new Label
{
Text = item.Title,
FontAttributes = FontAttributes.Bold,
TextColor = Color.White,
BackgroundColor = Color.FromHex("#00a8d5")
};
NavigationPage.SetTitleView(page, titleView);

For Android part, you could implement this feature by add the following in your Resources\values\styles.xml file:
<style name="ActionBar.nameText" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textSize">58sp</item> <-- Could delete this line
<item name="android:textStyle">bold</item>
</style>
Then, add it in your Resources\layout\Toolbar.axml:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:companyApp="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"
companyApp:titleTextAppearance="#style/ActionBar.nameText"/>

For IOS, you should simply do this. in FinishedLaunching of IOS project you need to put this UINavigationBar.Appearance.TitleTextAttributes = new UIStringAttributes()
{
Font = UIFont.SystemFontOfSize(18.0f, UIFontWeight.Heavy)
};
before LoadApplication(new App());

Related

Xamarin.Forms. How to add views on top of map, but right on the defined lat/lng position?

Currently i am developing a taxi app. But got to the point where i need to put some views on top of the map that will move when i move me map. I am wondering how it is possible to do it using Xamarin.Forms.GoogleMaps package. The inbuilt "Icon = BitmapDescriptorFactory.FromView()" won't work for me because i need a view that consists of two or more clickable parts + i don't want the views to overlap. Adding a picture of what i need to achieve. Any help would be appreciated
Here is the pic
Are you using Xamarin.Forms.Maps? https://www.nuget.org/packages/Xamarin.Forms.Maps/
This component makes it easier to work as you need.
In xaml file you need add this code:
>
<ContentView Content="{Binding Map}"/>
And in your viewModel add this code:
>
Map = new Map(MapSpan.FromCenterAndRadius(new Position(location.Latitude, location.Longitude), Distance.FromKilometers(1)));
To add pins, add this:
>
var pin = new Pin
{
Type = PinType.Place,
Address = String.Empty,
Label = item.Name,
Position = new Position(item.Geometry.Location.Lat, item.Geometry.Location.Lng),
};
pin.InfoWindowClicked += async (s, args) => { await PinClicked((Pin)s); };
Map.Pins.Add(pin);
Welcome to SO !
You can create a custom renderer for the Map control, which displays a native map with a customized pin and a customized view of the pin data on each platform.
Refer to this document :https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/map-pin#creating-the-custom-map
Android :
Custom the MapPlusInfo.xml in android native can achieve that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_vertical"
android:background="#android:color/white"
android:layout_marginRight="20dp">
<TextView
android:id="#+id/InfoWindowTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="InfoWindowTitle"
android:textColor="#android:color/black"
android:textStyle="bold" />
<TextView
android:id="#+id/InfoWindowSubtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="InfoWindowSubtitle"
android:textColor="#android:color/black" />
</LinearLayout>
<ImageButton
android:id="#+id/InfoWindowButton"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/plus" />
</LinearLayout>
The renderer code in Android :
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
{
List<CustomPin> customPins;
public CustomMapRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
}
}
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
}
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
return marker;
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.MapPlusInfo, null);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
else
{
//view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
}
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
}
The effect :

How to make multiline text on tab items in iOS

I got 5 tabs on TabbedPage & last 2 tabs have long title name, on Android, it shows 3dots as ... when there is no more room space remaining for text.
eg.
tab 1 title - Title 1 for Tab1
tab 2 title - Title 2 for Tab2
tab 3 title - Title 3 for Tab3
Android - Title 1 f... | Title 2 f... | Title 3 f...
But on iOS it doesn't show 3dots, it shows complete text which can even override the title of another tab. Kind of text overlapping.
Basically I want my title of TabbedPage on multi-line, I use different content pages as tabs for my TabbedPage.
I can create MultiLine ContentPage n its working fine on its own. But when I set the MultiLine title content page as a tab for my TabbedPage, it only shows the first-line title.
Any solution for MultiLine TabbedPage Title on iOS like below
My Current renderer code
[assembly: ExportRenderer( typeof( TabbedPage ), typeof(ExtendedTabbedPageRenderer ) )]
namespace testBlu.iOS.Renderers
{
public class ExtendedTabbedPageRenderer : TabbedRenderer
{
public override void ViewDidAppear( bool animated )
{
base.ViewDidAppear( animated );
if( TabBar.Items != null )
{
UITabBarItem[] tabs = TabBar.Items;
foreach( UITabBarItem tab in tabs )
{
UITextAttributes selectedColor = new UITextAttributes { TextColor = UIColor.Black };
UITextAttributes fontSize = new UITextAttributes { Font = UIFont.SystemFontOfSize( 12 )};
tab.SetTitleTextAttributes( selectedColor, UIControlState.Normal );
tab.SetTitleTextAttributes( fontSize, UIControlState.Normal );
}
}
}
}
}
If need to show three dots the same with Android , here is a solution for you . Later if have solution for multi-lines will update here .
You can use Custom TabbedRenderer to implement it .
[assembly: ExportRenderer(typeof(MainPage), typeof(ExtendedTabbedPageRenderer))]
namespace AppTab3.iOS
{
public class ExtendedTabbedPageRenderer : TabbedRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var tabs = Element as TabbedPage;
if(tabs != null)
{
for( int i = 0;i < TabBar.Items.Length;i++)
{
if (TabBar.Items[i] == null) return;
if(TabBar.Items[i].Title.Length > 6)
{
string showText = TabBar.Items[i].Title;
TabBar.Items[i].Title = showText.Substring(0, 5) + "...";
}
}
}
}
}
}
Here MainPage inside code is a TabbedPage :public partial class MainPage : TabbedPage
And here I set the limited length of TabBar Text is 6 . The Xaml is as follow :
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:views="clr-namespace:AppTab3.Views"
x:Class="AppTab3.Views.MainPage">
<TabbedPage.Children>
<NavigationPage Title="Browse">
<NavigationPage.Icon>
<OnPlatform x:TypeArguments="FileImageSource">
<On Platform="iOS" Value="tab_feed.png"/>
</OnPlatform>
</NavigationPage.Icon>
<x:Arguments>
<views:ItemsPage />
</x:Arguments>
</NavigationPage>
...
<NavigationPage Title="Page Five Long Title Page Five Long Title">
<NavigationPage.TitleView>
<Label Text="About Five Long Title" MaxLines="4"/>
</NavigationPage.TitleView>
<NavigationPage.Icon>
<OnPlatform x:TypeArguments="FileImageSource">
<On Platform="iOS"
Value="tab_about.png" />
</OnPlatform>
</NavigationPage.Icon>
<x:Arguments>
<views:AboutPage />
</x:Arguments>
</NavigationPage>
</TabbedPage.Children>
</TabbedPage>
The effect :
================================Update=============================
I have found the way to implement multiline title in tabbar item , need to modify code in TabbedRenderer as follow :
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var tabs = Element as TabbedPage;
if (tabs != null)
{
for (int i = 0; i < TabBar.Items.Length; i++)
{
if (TabBar.Items[i] == null) continue;
if (TabBar.Items[i].Title.Length > 6)
{
string[] splitTitle = TabBar.Items[i].Title.Split(" ");
TabBar.Items[i].Title = splitTitle[0] + "\n" + splitTitle[1];
UITabBarItem item = TabBar.Items[i] as UITabBarItem;
UIView view = item.ValueForKey(new Foundation.NSString("view")) as UIView;
UILabel label = view.Subviews[1] as UILabel;
//label.Text = "Hello\nWorld!";
label.Lines = 2;
label.LineBreakMode = UILineBreakMode.WordWrap;
//var frame = label.Frame;
//label.Frame = CGRect.FromLTRB(frame.Location.X, frame.Location.Y, frame.Size.Width, frame.Size.Height + 20);
}
}
}
}
The effect:
Note : Althouh this way can implement it , however Apple not recommands to do this . It will affect the beauty of interface ,and make the frame of Tabbar item's shape distortion .
=============================Update with shared code=======================
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var tabs = Element as TabbedPage;
if (tabs != null)
{
for (int i = 0; i < TabBar.Items.Length; i++)
{
if (TabBar.Items[i] == null) continue;
if (TabBar.Items[i].Title.Length > 6)
{
string[] splitTitle = TabBar.Items[i].Title.Split(" ");
if (null != splitTitle[1])
{
if (splitTitle[1].Length > 4)
{
string showText = splitTitle[1];
splitTitle[1] = showText.Substring(0, 3) + "...";
}
}
TabBar.Items[i].Title = splitTitle[0] + "\n" + splitTitle[1];
UITabBarItem item = TabBar.Items[i] as UITabBarItem;
UITextAttributes selectedColor = new UITextAttributes { TextColor = UIColor.Black };
UITextAttributes fontSize = new UITextAttributes { Font = UIFont.SystemFontOfSize(12) };
item.SetTitleTextAttributes(selectedColor, UIControlState.Selected);
item.SetTitleTextAttributes(fontSize, UIControlState.Selected);
UIView view = item.ValueForKey(new Foundation.NSString("view")) as UIView;
UILabel label = view.Subviews[1] as UILabel;
//label.Text = "Hello\nWorld!";
label.Lines = 2;
label.LineBreakMode = UILineBreakMode.WordWrap;
//var frame = label.Frame;
//label.Frame = CGRect.FromLTRB(frame.Location.X, frame.Location.Y, frame.Size.Width, frame.Size.Height + 10);
}
}
}
}
I think the most simple way (i.e, avoiding a custom renderer) would be to use a TitleView
Here's the official Microsoft sample.
https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/navigation-titleview/
Here's a blog post.
https://www.andrewhoefling.com/Blog/Post/xamarin-forms-title-view-a-powerful-navigation-view
In that TitleView you can use a Label and set the LineBreakMode property.

CustomPicker Ok and Cancel buttons' color

I have this custompicker class in android project:
public class CustomPickerRenderer : PickerRenderer
{
private Context context;
private IElementController ElementController => Element as IElementController;
private AlertDialog _dialog;
public CustomPickerRenderer(Context context) : base(context)
{
this.context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (Control == null || e.NewElement == null) return;
Control.Click += Control_Click1;
}
protected override void Dispose(bool disposing)
{
Control.Click -= Control_Click1;
base.Dispose(disposing);
}
private void Control_Click1(object sender, EventArgs e)
{
Picker model = Element;
var picker = new NumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetDisplayedValues(model.Items.ToArray());
picker.WrapSelectorWheel = false;
picker.DescendantFocusability = DescendantFocusability.BlockDescendants;
picker.Value = model.SelectedIndex;
}
var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
layout.AddView(picker);
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);
var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
//change the text or color here
builder.SetNegativeButton(Html.FromHtml("<font color='#039BE5'>Cancel</font>"), (s, a) =>
{
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
_dialog = null;
});
//change the text or color here
builder.SetPositiveButton(Html.FromHtml("<font color='#039BE5'>OK</font>"), (s, a) =>
{
ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
// It is possible for the Content of the Page to be changed on SelectedIndexChanged.
// In this case, the Element & Control will no longer exist.
if (Element != null)
{
if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
Control.Text = model.Items[Element.SelectedIndex];
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is also possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
}
_dialog = null;
});
_dialog = builder.Create();
_dialog.DismissEvent += (ssender, args) =>
{
ElementController?.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
};
_dialog.Show();
}
}
I tried running my project on my phone Xiaomi POCOPHONE F1 (Android 9) and 2 emulators (Android 8.1) and the colors of cancel and ok buttons are designed Perfectly. But when I tried running the project on Huawei PLE-701L and SAMSUNG SM-T365 (Android 5.1) the color of the buttons didn't changed.
Any suggestions?
Get the button object through the API of dialog and set the text color of the button. This method can be personalized. One point needs to be noted: it must be called after show
in your custom renderer,below _dialog.Show();
....
_dialog.Show();
Button btnOk = _dialog.GetButton((int)DialogInterface.ButtonPositive);
btnOk .SetTextColor(Color.Red);
Button btnCancel= _dialog.GetButton((int)DialogInterface.ButtonNegative);
btnCancel.SetTextColor(Color.Red);
add this style in style.xml
<style name="SpinnerDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="android:popupBackground">#ff00ff</item>
<item name="colorPrimary">#ff00ff</item>
<item name="colorPrimaryDark">#ffff00</item>
<item name="colorAccent">#ff0000</item>
</style>
you can change allthe color including buttons.
and you can also use
<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
<item name="android:colorPrimary">#1e87f0</item>
<item name="android:colorAccent">#1e87f0</item>
</style>
<style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">#1e87f0</item>
</style>
The Question is answered here: Picker button's color not changing on android 5.1
I added the styles code in the correct answer in the link, and it worked!

Change hamburger icon in master detail navigation xamarin forms

I am working on Xamarin forms where I need to show master detail navigation after successful login screen. I want to change default hamburger icon but not able to change it.
Please see below code I am using.
Since my app have login screen so I don't want to show any navigation on Login screen. I am just setting main page in app.xaml.cs
public App()
{
InitializeComponent();
MainPage = new Login();
}
Now after login clicked I tried following approach to change icon but didn't work
var dashboard = new Dashboard(){Icon = "Menuicon.png" };
Application.Current.MainPage = dashboard;
Dashbaord is masterdetail page and on its ctor, I am setting detail page like below
Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(DashbaordDetail))) { Icon = "Menuicon.png" };
Its not reflecting new icon
You should use a custom renderer.
In your Android project, like this:
[assembly: ExportRenderer(typeof(CustomIcon.Views.MainPage), typeof(IconNavigationPageRenderer))]
namespace CustomIcon.Droid
{
public class IconNavigationPageRenderer : MasterDetailPageRenderer
{
private static Android.Support.V7.Widget.Toolbar GetToolbar() => (CrossCurrentActivity.Current?.Activity as MainActivity)?.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
var toolbar = GetToolbar();
if (toolbar != null)
{
for (var i = 0; i < toolbar.ChildCount; i++)
{
var imageButton = toolbar.GetChildAt(i) as ImageButton;
var drawerArrow = imageButton?.Drawable as DrawerArrowDrawable;
if (drawerArrow == null)
continue;
imageButton.SetImageDrawable(Forms.Context.GetDrawable(Resource.Drawable.newIcon));
}
}
}
}
}
In your iOS project only use the same icon from you xaml file in your PCL project, like this:
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CustomIcon.Views;assembly=CustomIcon"
Title="MainPage"
Icon="newIcon.png"
x:Class="CustomIcon.Views.MainPage">
<MasterDetailPage.Master>
<local:MasterPage x:Name="masterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<x:Arguments>
<local:Page1 />
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
For more information see my repo on github: https://github.com/wilsonvargas/CustomIconNavigationPage
i applied this tweak and it helped me. now i can see back button also after navigation
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
{
for (var i = 0; i < toolbar.ChildCount; i++)
{
var imageButton = toolbar.GetChildAt(i) as ImageButton;
var drawerArrow = imageButton?.Drawable as DrawerArrowDrawable;
if (drawerArrow == null)
continue;
bool displayBack = false;
var app = Xamarin.Forms.Application.Current;
var detailPage = (app.MainPage as MasterDetailPage).Detail;
var navPageLevel = detailPage.Navigation.NavigationStack.Count;
if (navPageLevel > 1)
displayBack = true;
if (!displayBack)
ChangeIcon(imageButton, Resource.Drawable.iconMenu2);
if (displayBack)
ChangeIcon(imageButton, Resource.Drawable.back1);
}
}
}
private void ChangeIcon(ImageButton imageButton, int id)
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
imageButton.SetImageDrawable(Context.GetDrawable(id));
imageButton.SetImageResource(id);
}

Xamarin forms MasterDetailPage navigation

So ive been working on an app that uses a MasterDetail page and its going fine but Im just a little bit confused on how its suppose to navigate through pages.
At the moment i have the menu items opening some pages in the app and that parts working great, the side menu stays. The thing im confused with is how to handle having buttons on the main page being displayed. My buttons at the moment just open up a new page but the side menu of the MasterDetail page just disappears into the regular NavigationPage.
I will give my button code below.
btnSocial.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = new Command(() =>
{
Navigation.PushAsync(new SocialPage());
})
});
Is this just how a MasterDetail page navigates or do you think im doing something wrong?
** EDITED **
Just incase this helps, i will attach my menuopage and launchpage code:
MenuPage.cs
public class MenuPage : ContentPage
{
public Action<ContentPage> OnMenuSelect { get; set; }
public MenuPage()
{
Title = "Menu";
Icon = "ic_menu.png";
BackgroundColor = ProjectVariables.PRIMARY_COLOR;
var items = new List<MenuItems>()
{
new MenuItems("Social", () => new SocialPage()),
new MenuItems("Career", () => null),
new MenuItems("MySchedule", () => null),
new MenuItems("Videos", () => null),
new MenuItems("Contact", () => null),
new MenuItems("Sign in", () => null)
};
var dataTemplate = new DataTemplate(typeof(TextCell));
dataTemplate.SetValue(TextCell.TextColorProperty, Color.White);
dataTemplate.SetBinding(TextCell.TextProperty, "Name");
var listview = new ListView()
{
ItemsSource = items,
ItemTemplate = dataTemplate
};
listview.BackgroundColor = ProjectVariables.PRIMARY_COLOR;
listview.ItemSelected += (object sender, SelectedItemChangedEventArgs e) =>
{
if(OnMenuSelect != null)
{
var item = (MenuItems)e.SelectedItem;
var itemPage = item.PageFn();
OnMenuSelect(itemPage);
}
};
Content = new StackLayout
{
Orientation = StackOrientation.Vertical,
Children =
{
listview
}
};
}
}
LaunchPage.cs
public class LaunchPage : MasterDetailPage
{
public LaunchPage()
{
var menuPage = new MenuPage();
menuPage.OnMenuSelect = (categoryPage) =>
{
Detail = new NavigationPage(categoryPage);
//Detail.Navigation.PushAsync(categoryPage);
IsPresented = false;
};
Master = menuPage;
Detail = new NavigationPage(new MainPage())
{
BarTextColor = Color.White,
BarBackgroundColor = ProjectVariables.PRIMARY_COLOR
};
MasterBehavior = MasterBehavior.Split;
}
}
Have a look at this documentation page from Xamarin.
It looks like you do not use the navigation service for this. You need a reference to your master page and set the Detail property for it.
Look at this section in particular.
public partial class MainPage : MasterDetailPage
{
public MainPage ()
{
...
masterPage.ListView.ItemSelected += OnItemSelected;
}
void OnItemSelected (object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MasterPageItem;
if (item != null) {
Detail = new NavigationPage ((Page)Activator.CreateInstance (item.TargetType));
masterPage.ListView.SelectedItem = null;
IsPresented = false;
}
}
}
On the selection of a ListView item they set the Detail property and it will do the navigation for you.

Resources