I working on Xamarin.Forms and i need to change name of "More" tab on tabbed page. How I can do that ?
I working on Xamarin.Forms and i need to change name of "More" tab on tabbed page. How I can do that ?
You can use custom render to change TabbedPage "More" Tab in Android project, take a look the following code:
[assembly: ExportRenderer(typeof(TabbedPage), typeof(MyTabbedPageRenderer))]
namespace gensture.Droid
{
public class MyTabbedPageRenderer : TabbedPageRenderer
{
Xamarin.Forms.TabbedPage tabbedPage;
BottomNavigationView bottomNavigationView;
public MyTabbedPageRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
tabbedPage = e.NewElement as TabbedPage;
bottomNavigationView = (GetChildAt(0) as Android.Widget.RelativeLayout).GetChildAt(1) as BottomNavigationView;
ChangeFont();
}
}
void ChangeFont()
{
var bottomNavMenuView = bottomNavigationView.GetChildAt(0) as BottomNavigationMenuView;
for (int i = 0; i < bottomNavMenuView.ChildCount; i++)
{
var item = bottomNavMenuView.GetChildAt(i) as BottomNavigationItemView;
var itemTitle = item.GetChildAt(1);
var smallTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(0));
var largeTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(1));
if(smallTextView.Text=="More" && largeTextView.Text=="More")
{
smallTextView.Text = "test";
largeTextView.Text = "test";
}
}
}
}
}
The screenshot:
Update:
You need to make TabbedPage.ToolbarPlacement="Bottom", to make "More Tab" appear.
<TabbedPage
x:Class="gensture.TabbedPage1"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
android:TabbedPage.BarItemColor="#999999"
android:TabbedPage.BarSelectedItemColor="Black"
android:TabbedPage.ToolbarPlacement="Bottom">
<!-- Pages can be added as references or inline -->
<ContentPage Title="Tab 1" />
<ContentPage Title="Tab 2" />
<ContentPage Title="Tab 3" />
<ContentPage Title="Tab 4" />
<ContentPage Title="Tab 5" />
<ContentPage Title="Tab 6" />
Related
I have a Picker in Xamarin and I want to go to the page which is selected in Picker. So here is my view in Picker:
<ContentPage.Content>
<ScrollView>
<StackLayout Margin="20">
<Label Text="List of tables" FontAttributes="Bold" HorizontalOptions="Center"/>
<Picker Title="Select table" ItemsSource="{Binding TablesFromViewModelCollector}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedTable}" />
<Label Text="{Binding SelectedTable.Name}" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}"/>
<Button Text="Select Table" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}" Clicked="Selected_Button"/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
Here is it's contoller:
public TablePage()
{
InitializeComponent();
BindingContext = new TableViewModel();
}
async void Selected_Button(object sender, System.EventArgs e)
{
await Navigation.PushAsync(new TableDetails());
}
And here is TableViewModel where I can select the table from Picker:
class TableViewModel : INotifyPropertyChanged
{
public IList<Table> TablesFromViewModelCollector { get { return TableData.Tables; } }
Table selectedTable;
public Table SelectedTable
{
get { return selectedTable; }
set
{
if(SelectedTable != value)
{
selectedTable = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
So I added button under the Picker as you see. And what I am trying to achieve, when the Picker is selected and button is clicked, goes to the page of TableDetails. In this page, I want to show the data of selectedTable. Basically, here is my view for TableDetails:
<ContentPage.Content>
<ScrollView>
<StackLayout Margin="20">
<Label Text="{Binding SelectedTable.Name}" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}"/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
And here is my controller:
public partial class TableDetails : ContentPage
{
public TableDetails()
{
InitializeComponent();
BindingContext = new TableViewModel();
}
}
But I dont get the value of the selectedTable.
just pass the value on the constructor
await Navigation.PushAsync(new TableDetails(VM.SelectedTable));
then modify the page constructor
public TableDetails(Table selected)
{
InitializeComponent();
BindingContext = new TableViewModel();
}
I have a Xamarin Forms App with a Carousel View and my plan is to filter the result by the Priorities shown in a Bottom Tap Bar.
When the View is on the first card, everything works fine, but if you hit one of the filters from a different card, then the first one, a System.ArgumentOutOfRangeException exception got fired.
I tried already a lot of things to set the position of the Carousel View to 0, but in vain.
using the CarouselView_PositionChanged event => not working
using the TabHost_SelectedTabIndexChanged event => not working
setting the property of the CarouselView by the selectedIndex changed from the Tab View from the ViewModel => not working
turn it into a CollectionView and everything is working => just looks ugly 🤮
Here the page
<?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:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
xmlns:viewModels="clr-namespace:AmsXamarin.ViewModels"
xmlns:fontAwesome="clr-namespace:FontAwesome"
xmlns:cells="clr-namespace:AmsXamarin.Cells"
xmlns:tabs="http://sharpnado.com"
xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
x:Class="AmsXamarin.Views.SnagListX.SnagListPage"
x:Name="mySnagListPage">
<ContentPage.BindingContext>
<viewModels:SnagListViewModel />
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<xct:TabSelectionChangedEventArgs x:Key="TabSelectionChangedEventArgs" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.ToolbarItems>
<ToolbarItem Command="{Binding ShowMyJobsCommand}"
Order="Primary"
Priority="0"
Text="{Binding MyJobsTitle,Mode=TwoWay}">
</ToolbarItem>
<ToolbarItem Command="{Binding AddFaultCommand}"
Order="Primary"
Priority="0">
<ToolbarItem.IconImageSource>
<FontImageSource FontFamily="FAS"
Glyph="{x:Static fontAwesome:FontAwesomeIcons.Plus}"
Color="{AppThemeBinding Dark={StaticResource Third},Light={StaticResource Primary}}"
Size="Large" />
</ToolbarItem.IconImageSource>
</ToolbarItem>
<ToolbarItem Command="{Binding AcceptCommand}"
Order="Primary"
Priority="0">
<ToolbarItem.IconImageSource>
<FontImageSource FontFamily="FAS"
Glyph="{x:Static fontAwesome:FontAwesomeIcons.UserCheck}"
Color="{AppThemeBinding Dark={StaticResource Third},Light={StaticResource Primary}}"
Size="Large" />
</ToolbarItem.IconImageSource>
</ToolbarItem>
</ContentPage.ToolbarItems>
<ContentPage.Content>
<StackLayout>
<Label Style="{StaticResource LabelLarge}"
Text="Snag List"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<StackLayout>
<IndicatorView x:Name="snagListIndicator"
Margin="0,10,0,0"
IndicatorColor="LightGray"
SelectedIndicatorColor="LightGray"
IndicatorSize="6" />
<RefreshView Command="{Binding RefreshCommand}"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
Style="{StaticResource BaseRefreshView}">
<CarouselView x:Name="snagListCV"
Margin="10"
IndicatorView="snagListIndicator"
ItemsLayout="HorizontalList"
ItemsSource="{Binding SnagListPriorities.SnagListApps}"
CurrentItem="{Binding SnagListItem}"
Position="{Binding PositionIdx,Mode=OneWay}"
PositionChanged="CarouselView_PositionChanged"
Loop="False"
IsEnabled="{Binding IsNotBusy}">
<CarouselView.EmptyView>
<StackLayout Padding="12">
<Label Style="{StaticResource LabelMedium}"
HorizontalOptions="Center"
Text="{Binding EmptyMessage,Mode=TwoWay}" />
</StackLayout>
</CarouselView.EmptyView>
<CarouselView.ItemTemplate>
<DataTemplate>
<cells:SnagListCardX />
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</RefreshView>
</StackLayout>
<tabs:TabHostView x:Name="TabHost"
Margin="13,0,13,10"
BackgroundColor="{AppThemeBinding Dark={StaticResource Third},Light={StaticResource Fourth}}"
CornerRadius="30"
IsSegmented="True"
Orientation="Horizontal"
TabType="Fixed"
SelectedIndex="{Binding SelectedIndex,Mode=TwoWay}"
Shades="{StaticResource LightBottomShadow}">
<tabs:TabHostView.Behaviors>
<xct:EventToCommandBehavior EventName="SelectedTabIndexChanged"
Command="{Binding SelectedCommand}"
EventArgsConverter="{StaticResource TabSelectionChangedEventArgs}" />
</tabs:TabHostView.Behaviors>
<tabs:TabHostView.Tabs>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="All">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource All}"
TextColor="White"
Text="{Binding SnagListPriorities.All,Mode=TwoWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="High"
StyleClass="">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource High}"
TextColor="White"
Text="{Binding SnagListPriorities.High,Mode=OneWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="Medium">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource Medium}"
TextColor="Black"
Text="{Binding SnagListPriorities.Medium,Mode=TwoWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="Low">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource Low}"
TextColor="Black"
Text="{Binding SnagListPriorities.Low,Mode=TwoWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
</tabs:TabHostView.Tabs>
</tabs:TabHostView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
And the view model
using AmsXamarin.Helpers;
using AmsXamarin.Models;
using AmsXamarin.Services;
using MvvmHelpers;
using MvvmHelpers.Commands;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Command = MvvmHelpers.Commands.Command;
namespace AmsXamarin.ViewModels
{
public class SnagListViewModel : BaseViewModel
{
readonly ISnagListService snagListService;
List<SnagListAppX> SnagListAppXs;
SnagListAppX snagListItem;
public SnagListAppX SnagListItem
{
get { return snagListItem; }
set
{
snagListItem = value;
OnPropertyChanged();
}
}
SnagListPriorities snagListPriorities;
public SnagListPriorities SnagListPriorities
{
get { return snagListPriorities; }
set
{
snagListPriorities = value;
OnPropertyChanged();
}
}
public AsyncCommand AddFaultCommand { get; }
public AsyncCommand AcceptCommand { get; }
public Command RefreshCommand { get; }
public Command SelectedCommand { get; }
public Command ShowMyJobsCommand { get; }
string emptyMessage;
public string EmptyMessage
{
get { return emptyMessage; }
set
{
emptyMessage = value;
OnPropertyChanged();
}
}
int positionIdx;
public int PositionIdx
{
get { return positionIdx; }
set
{
positionIdx = value;
OnPropertyChanged();
}
}
int selectedIndex;
public int SelectedIndex
{
get => selectedIndex;
set => SetProperty(ref selectedIndex, value);
}
string myJobsTitle = "My Jobs";
int staffId;
public string MyJobsTitle
{
get { return myJobsTitle; }
set
{
myJobsTitle = value;
OnPropertyChanged();
}
}
bool myJobsEnabled = true;
bool updateProperty = false;
public bool AcceptToolBar { get; set; }
public SnagListViewModel()
{
SnagListItem = new SnagListAppX();
SnagListPriorities = new SnagListPriorities()
{
SnagListApps = new ObservableRangeCollection<SnagListAppX>()
};
SnagListAppXs = new List<SnagListAppX>();
AddFaultCommand = new AsyncCommand(ShowAddSnagListItem);
AcceptCommand = new AsyncCommand(ShowModalAccept);
SelectedCommand = new Command(Selected);
RefreshCommand = new Command(Refresh);
staffId = 0;
ShowMyJobsCommand = new Command(ShowModalMyJobs);
snagListService = DependencyService.Get<ISnagListService>();
Device.BeginInvokeOnMainThread(async () =>
{
await GetSnagListItems();
});
}
async Task GetSnagListItems()
{
try
{
IsBusy = true;
EmptyMessage = "Loading...";
SnagListPriorities slp = await snagListService.GetSnagLists(false, true);
SnagListPriorities.SnagListApps.Clear();
SnagListPriorities = slp;
SnagListAppXs.Clear();
SnagListAppXs.AddRange(slp.SnagListApps);
EmptyMessage = SnagListAppXs.Count == 0 ? "Good Job! \r\n\r\nCurrently nothing to fix" : "";
IsBusy = false;
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "Ok");
}
}
void Selected()
{
//PositionIdx = 0;
//OnPropertyChanged(nameof(PositionIdx));
//FilterSnagList();
Refresh();
}
void FilterSnagList()
{
var allJobs = SnagListAppXs;
if (staffId != 0) allJobs = allJobs.Where(x => x.StaffId == staffId).ToList();
if (updateProperty) OnPropertyChanged(nameof(SnagListPriorities));
if (selectedIndex > 0) allJobs = allJobs.Where(sli => sli.Priority == selectedIndex).ToList();
SnagListPriorities.SnagListApps.Clear();
//SnagListPriorities.SnagListApps = new ObservableRangeCollection<SnagListAppX>(allJobs);
SnagListPriorities.SnagListApps.AddRange(allJobs);
//OnPropertyChanged(nameof(SnagListPriorities.SnagListApps));
updateProperty = false;
}
void ShowModalMyJobs()
{
staffId = myJobsEnabled ? int.Parse(Settings.StaffIdSetting) : 0;
MyJobsTitle = myJobsEnabled ? "All Jobs" : "My Jobs";
AcceptToolBar = !myJobsEnabled;
myJobsEnabled = !myJobsEnabled;
SelectedIndex = 0;
updateProperty = true;
}
void Refresh()
{
IsBusy = true;
var allJobs = SnagListAppXs.Where(s => s.StaffId == 115);
SnagListPriorities.SnagListApps.Clear();
SnagListPriorities.SnagListApps.AddRange(allJobs);
IsBusy = false;
}
}
}
looks a bit messy, but wanted to show, that I tried already a lot of things.
Last try was a simple RefreshView.
It works as long as the itemsSource is not changing. Once it changes and the first card is not shown, it crashes.
Any ideas? Many thanks
For this example:
var vm.MyText = "ABC";
<Label Grid.Row="1" Text="{Binding MyText}" />
Is there a way that I can add an underscore to the text?
use TextDecorations="Underline" (requires 3.3.0)
<Label>
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="This app is written in C#, XAML, and native APIs using the" />
<Span Text=" " />
<Span Text="Xamarin Platform" FontAttributes="Bold" TextColor="Blue" TextDecorations="Underline">
<Span.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding TapCommand, Mode=OneWay}"
CommandParameter="https://learn.microsoft.com/en-us/xamarin/xamarin-forms/"/>
</Span.GestureRecognizers>
</Span>
<Span Text="." />
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
You can use a FormattedString to apply different attributes, colors, etc.. to a label:
var formattedString = new FormattedString();
formattedString.Spans.Add(new Span { Text = "Stack, ", FontAttributes = FontAttributes.None });
formattedString.Spans.Add(new Span { Text = "Overflow, ", FontAttributes = FontAttributes.Italic });
label.FormattedText = formattedString;
re: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/label#formatted-text
Edit: check this answer if you're running a XF version previous to 3.3.0, otherwise followe the accepted answer.
If you need is an underline, you must create an effect
using Xamarin.Forms;
namespace YourProjectNamespace.Effects
{
public class UnderlineTextEffect : RoutingEffect
{
public UnderlineTextEffect()
: base("YourProjectNamespace.UnderlineTextEffect")
{
}
}
}
Android implementation
using System;
using System.ComponentModel;
using Android.Graphics;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ResolutionGroupName("YourProjectNamespace")]
[assembly: ExportEffect(typeof(AndroidUnderlineTextEffect), "UnderlineTextEffect")]
namespace YourProjectNamespace.Android.Effects
{
public class AndroidUnderlineTextEffect : PlatformEffect
{
protected override void OnAttached()
{
((TextView)Control).PaintFlags |= PaintFlags.UnderlineText;
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
if (args.PropertyName == Label.TextProperty.PropertyName || args.PropertyName == Label.FormattedTextProperty.PropertyName)
((TextView)Control).PaintFlags |= PaintFlags.UnderlineText;
}
}
}
iOS implementation:
using System;
using System.ComponentModel;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ResolutionGroupName("YourProjectNamespace")]
[assembly: ExportEffect(typeof(AppleUnderlineTextEffect), "UnderlineTextEffect")]
namespace YourProjectNamespace.iOS.Effects
{
public class AppleUnderlineTextEffect : PlatformEffect
{
protected override void OnAttached()
{
SetTextUnderline();
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
if (args.PropertyName == Label.TextProperty.PropertyName || args.PropertyName == Label.FormattedTextProperty.PropertyName)
SetTextUnderline();
}
private void SetTextUnderline()
{
var text = ((UILabel)Control).AttributedText as NSMutableAttributedString;
var range = new NSRange(0, text.Length);
text.AddAttribute(UIStringAttributeKey.UnderlineStyle,
NSNumber.FromInt32((int)NSUnderlineStyle.Single),
range);
}
}
}
And on your XAML add the effect:
<?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:local="clr-namespace:YourProjectNamespace"
x:Class="YourProjectNamespace.UnderlineEffectPage">
<StackLayout>
<Label
HorizontalOptions="FillAndExpand"
VerticalOptions="CenterAndExpand"
Text="Underlined Text">
<Label.Effects>
<local:UnderlineTextEffect />
</Label.Effects>
</Label>
</StackLayout>
</ContentPage>
I wrote this code to try and show a couple of lines of HTML within a web page:
I have this XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Japanese;assembly=Test"
x:Class="Test.HelpCards"
x:Name="HelpCards"
Title="Help â–¹ Cards Tab">
<ContentPage.Content>
<ScrollView>
<StackLayout Spacing="10" Margin="20">
<WebView x:Name="Browser" />
</StackLayout>
</ScrollView>
</ContentPage.Content>
</ContentPage>
public HelpCards()
{
InitializeComponent();
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = #"<html><body>
<h1>ABC</h1>
<p>DEF</p>
</body></html>";
Browser.Source = htmlSource;
}
However when running the code I see only a blank page.
Does anyone have any ideas as to what might be wrong?
Make sure to specify layout-options for WebView.
<ContentPage.Content>
<ScrollView> <!-- ScrollView not needed as WebView has inbuilt scrolling behavior -->
<StackLayout Spacing="10" Margin="20">
<WebView x:Name="Browser" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
</StackLayout>
</ScrollView>
</ContentPage.Content>
Xamarin has updated the label element at some point. The update included a way to display HTML in the label element, by adding TextType="Html" to the element.
Example:
<Label TextType="Html">
<![CDATA[
This is <strong style="color:red">HTML</strong> text.
]]>
</Label>
(Source: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/label#display-html)
The webview can be in the ContentPage.Content by itself. No need to wrap it in a ScrollView or StackLayout. This method also doesn't require Horizontal or Vetical Options to be specified as well.
<ContentPage.Content>
<WebView x:Name="Browser" />
</ContentPage.Content>
Try this with the webBrowser
public MainPage()
{
InitializeComponent();
CheckWifiOnStart();
CheckWifiContinously();
}
private void CheckWifiOnStart()
{
var source = new HtmlWebViewSource();
source.BaseUrl = "file://android_asset/";
//CONTROL TO SEE IF USER IS CONNECTED
if (!CrossConnectivity.Current.IsConnected)
{
Browser.Source = "file:///android_asset/index.html";
}
else
{
Browser.Source = "ONLINE URL";
}
}
private void CheckWifiContinously()
{
var source = new HtmlWebViewSource();
source.BaseUrl = "file://android_asset/";
//CONTROL TO CONNECTIVITY CHANGE
CrossConnectivity.Current.ConnectivityChanged += (sender, args) => {
if (!CrossConnectivity.Current.IsConnected)
{
DisplayAlert("ERROR", "OFFLINE MODE", "OK");
Browser.Source = "file:///android_asset/index.html";
}
else
{
DisplayAlert("INTERNET DETECTED", "ONLINE MODE", "OK");
Browser.Source = "ONLINE URL";
}
};
}
public interface IBaseUrl { string GetFile(); }
I have a MDPage which is a MasterDetailPage which calls side menu items list page as Master. The Detail for this is added with a new NavigationPage of a home page.
My code is
public MDPage(){
Master = new SideMenuPage();
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;
Detail = new NavigationPage(new HomePage())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};}
I have a requirement where the NavigationPage contains a bottom menu such that on clicking a bottom menu, the MDPage needs to be reinitialized to set a new NavigationPage of a different page (say AboutUs page). So i added a parameterized constructor for MDPage and on clicking the bottom menu item i am calling App.Current.MainPage = new MDPage("AboutUs").Below is the parameterized constructor.
public MDPage(string bottomMenuItem)
{
Master = new SideMenuPage();
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;
if("AboutUs" == bottomMenuItem)
{
Detail = new NavigationPage(new AboutUs())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};
}}
Here the MDPage constructor is called initially when i open the app. Then from the side menu i have the option to open a HomePage which is added as Detail. Note that this HomePage contains a bottom sub menu, which is nothing but an image. On tapping this, it should again reinitialize the MDPage. Here this is working fine in Andorid. But in iOS, it is throwing null exception. It is not allowing me to set Master = new SideMenuPage(); I have found the root cause by trial and error as this code will not throw exception and it is throwing in the iOS Main.cs file. Please help me.
MainPage - XAML
<?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:ClubApp.Views;assembly=ClubApp"
x:Class="ClubApp.Views.MainPage">
<MasterDetailPage.Master>
<local:MasterPage x:Name="masterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<x:Arguments>
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
MainPage.xaml.cs
using System.Linq;using System.Text;using System.Threading.Tasks;using Xamarin.Forms;namespace Test.Views{
public partial class MainPage : MasterDetailPage
{
public MainPage()
{
Master = new MasterPage();
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;
Detail = new NavigationPage(new Views.HomePage())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};
}
public MainPage(string bottomMenu)
{
Master = new MasterPage();
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;
if ("News" == bottomMenu)
{
Detail = new NavigationPage(new Views.HomePage())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};
}
else if ("Profile" == bottomMenu)
{
Detail = new NavigationPage(new Views.Profile())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};
}
}
async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
try
{
var item = e.SelectedItem as MasterPageItem;
if (item != null)
{
if (item.Title == "News")
{
Detail = new NavigationPage(new Views.NewsPage())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};
}
if (item.Title == "Home")
{
Detail = new NavigationPage(new Views.HomePage())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};
}
if (item.Title == "Profile")
{
Detail = new NavigationPage(new Views.Profile())
{
BarBackgroundColor = Color.Black,
BarTextColor = Color.White,
};
}
masterPage.ListView.SelectedItem = null;
IsPresented = false;
}
}
catch (Exception ex)
{
}
}
}}
MasterPage.xaml
<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Test.Views.MasterPage"> <ContentPage.Content>
<StackLayout VerticalOptions="FillAndExpand" BackgroundColor="#10000c" Padding = "0,50,0,0" >
<StackLayout x:Name="slUserProfile" Orientation="Vertical" Spacing = "0"
VerticalOptions="FillAndExpand">
<Image Source="{Binding member_image}" x:Name="imgSideImage"
HorizontalOptions="CenterAndExpand" Aspect="AspectFill" HeightRequest="100"
WidthRequest="100" />
<Label Text="{Binding name}" TextColor="#efa747"
FontSize ="17"
HorizontalOptions="CenterAndExpand"/>
</StackLayout >
<ListView x:Name="lvSideMenu" VerticalOptions="FillAndExpand" SeparatorVisibility="None"
BackgroundColor="Black">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="15,5,0,0" Orientation="Horizontal">
<Image Source="{Binding IconSource}"/>
<StackLayout Padding = "10,0,0,0">
<local:CustomLabel Text="{Binding Title}" VerticalOptions="CenterAndExpand"
TextColor="#dac6ac" FontSize ="14"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout></ContentPage.Content></ContentPage>
MasterPage.xaml.cs
using Xamarin.Forms;namespace Test.Views{
public partial class MasterPage : ContentPage
{
public ListView ListView { get { return lvSideMenu; } }
public Page Detail { get; set; }
public MasterPage()
{
InitializeComponent();
var masterPageItems = new List<MasterPageItem>();
//Fills side menu items.
masterPageItems.Add(new MasterPageItem
{
Title = "Profile",
IconSource = "profile_sidemenu.png"
});
masterPageItems.Add(new MasterPageItem
{
Title = "Home",
IconSource = "home_smenu.png"
});
masterPageItems.Add(new MasterPageItem
{
Title = "News",
IconSource = "news_smenu.png"
});
lvSideMenu.ItemsSource = masterPageItems;
Icon = "menu.png";
Title = "Menu";
}
}
public class MenuItems
{
public string MenuTitle { get; set; }
}
public class MasterPageItem
{
public string Title { get; set; }
public string IconSource { get; set; }
}}
HomePage.xaml
<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Test.Views.HomePage" Title="Home"><ContentPage.Content><StackLayout> <Label Text="This is Home page"/></StackLayout></ContentPage.Content></ContentPage>
Profile.xaml
<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Test.Views.Profile" Title="Profile"><ContentPage.Content> <StackLayout>
<StackLayout>
<Label Text="This is Profile page" />
</StackLayout>
<StackLayout HeightRequest="80">
<Grid RowSpacing="0" ColumnSpacing="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackLayout x:Name="tProfile" BackgroundColor="Red" Grid.Column="0" Spacing="0" Padding="0,10,0,10">
<Image Source="bprofileSel.png" HorizontalOptions="Center" VerticalOptions="End"/>
<Label Text="Profile" FontSize="10" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center"/>
</StackLayout>
<StackLayout x:Name="tNews" BackgroundColor="Black" Grid.Column="1" Spacing="0" Padding="0,10,0,10">
<Image Source="bNewsUnsel.png" HorizontalOptions="Center" VerticalOptions="End"/>
<local:CustomLabel Text="News" FontSize="10" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center"/>
</StackLayout>
</Grid>
</StackLayout>
</StackLayout></ContentPage.Content></ContentPage>
Profile.xaml.cs
Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Xamarin.Forms;namespace Test.Views{
public partial class Profile : ContentPage
{
public Profile()
{
InitializeComponent();
try
{
tProfile.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = new Command(() => ProfileClicked()),
});
tNews.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = new Command(() => NewsClicked()),
});
}
catch (Exception ex)
{
}
}
private void ProfileClicked()
{
App.Current.MainPage = new MainPage("Profile");
}
private void NewsClicked()
{
App.Current.MainPage = new MainPage("News");
}
}}
News page can be set similar to the profile page. In app.cs call MainPage = new MainPage()
Here when the app is launched, it will show the HomePage with the side menu. Now when i click a menu (say profile from side menu), it will take me to the profile page and according to the design a bottom submenus can be seen there. Clicking on it will cause the null exception occurring in iOS code. This is working fine in android. My assumption is the root cause is due to MasterPage reinitialization to Master. But i need this requirement to be flown like this. Please help me.
This is the error in iOS Main.cs