Custom renderer for Toolbar Items not working for TabbedPage - xaml

I have 2 toolbar items in tabbed page (with two tabs).
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage
xmlns="bla"
xmlns:x="bla"
xmlns:views="clr-namespace:TestApp.Views"
x:Class="TestApp.Views.MyTabbedPage"
>
<views:Page1 Title="Page 1" />
<views:Page 2 Title="Page 2" />
</TabbedPage>
I am trying to move one toolbar item on left using custom renderer:
assembly: ExportRenderer(typeof(MyTabbedPage), typeof(TabbedPageRenderer))]
namespace TestApp.iOS
{
public class TabbedPageRenderer : TabbedRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var navigationItem = this.NavigationController.TopViewController.NavigationItem;
if (navigationItem.RightBarButtonItems.Length > 1)
{
navigationItem.LeftBarButtonItems = new UIBarButtonItem[] { navigationItem.RightBarButtonItems[1] };
}
navigationItem.RightBarButtonItems = new UIBarButtonItem[] { navigationItem.RightBarButtonItems[0]};
}
}
}
it works fine when page is loaded for first time. But when I click on tab to show the Page 2, It renders both toolbar items on right again (item on left stays at left) resulting in 3 toolbar items.
Can anyone please help me with this small issue?
Cheers

Related

In .NET MAUI is there a way to choose a different XAML view based upon whether the device is in Landscape or Portrait

I am using .NET MAUI and I have a particular view that is rather complicated and I would rather have a different layout if the device orientation is in Portrait vs if the device orientation is in landscape.
I tinkered around with Android programming a long time ago and for Android Studio there was a way to choose a XAML file when the device was in landscape and a different XAML file when the device was in portrait.
Is this possible with MAUI?
If not what is the best practice in regards to this?
Here is my layout and in landscape mode I can fit 3 major sections in one row but this won't work in portrait and in portrait I would like the middle major element to be on the next row.
Here are examples of my portrait vs landscape mockup I created on Photoshop:
UPDATE WITH SOLUTION***************
I'm attempting the solution that FreakyAli posted and have a mostly working prototype, so anyone who is wanting to use a different XAML layout based upon the screen orientation can use this approach.
I created a new folder called "ContentViews" in my solution.
I added 3 new ContentViews (the XAML with the code behind):
HomePageLandscape
HomePagePortrait
HomePageOrientationViewLoader
The HomePageOrientationViewLoader will get loaded directly into the HomePage.xaml file later on. This is the control that will load either the HomePagePortrait ContentView when in portrait mode or HomePageLandscape ContentView when in landscape mode.
namespace ScoreKeepersBoard.ContentViews;
public partial class HomePageOrientationViewLoader : ContentView
{
public ContentView homePagePortraitContentView;
public ContentView homePageLandscapeContentView;
public HomePageOrientationViewLoader()
{
InitializeComponent();
homePagePortraitContentView = new HomePagePortrait();
homePageLandscapeContentView = new HomePageLandscape();
this.Content = homePageLandscapeContentView;
DeviceDisplay.Current.MainDisplayInfoChanged += Current_MainDisplayInfoChanged;
this.Content = DeviceDisplay.Current.MainDisplayInfo.Orientation == DisplayOrientation.Portrait ? homePagePortraitContentView : homePageLandscapeContentView;
}
private void Current_MainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
if (e.DisplayInfo.Orientation == DisplayOrientation.Landscape)
{
// if (this.Content.GetType() is not typeof(HomePageLandscape))
// {
this.Content = homePageLandscapeContentView;
// }
}
else if (e.DisplayInfo.Orientation == DisplayOrientation.Portrait)
{
// if (this.Content.GetType() is not typeof(HomePagePortrait))
// {
this.Content = homePagePortraitContentView;
// }
}
else
{
//Whatever you would like to do if the orientation is unknown.
}
}
}
The HomePageOrientationViewLoader.xaml file:
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ScoreKeepersBoard.ContentViews.HomePageOrientationViewLoader">
<VerticalStackLayout>
<Label
Text="Welcome to .NET MAUI!"
VerticalOptions="Center"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ContentView>
Here is the HomePagePortrait.xaml.cs file:
namespace ScoreKeepersBoard.ContentViews;
public partial class HomePagePortrait : ContentView
{
public HomePagePortrait()
{
InitializeComponent();
}
}
Here is the HomePagePortrait.xaml file:
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ScoreKeepersBoard.ContentViews.HomePagePortrait">
<VerticalStackLayout>
<Label
Text="Welcome to .NET MAUI portrait"
VerticalOptions="Center"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ContentView>
Here is the HomePageLandscape.xaml.cs file:
namespace ScoreKeepersBoard.ContentViews;
public partial class HomePageLandscape : ContentView
{
public HomePageLandscape()
{
InitializeComponent();
}
}
Here is the HomePageLandscape.xaml file:
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ScoreKeepersBoard.ContentViews.HomePageLandscape">
<VerticalStackLayout>
<Label
Text="Welcome to .NET MAUI landscape"
VerticalOptions="Center"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ContentView>
My project had an initial home Content Page called HomePage. We are loading the HomePageOrientationViewLoader ContentView into the xaml of HomePage Content Page as a custom control. Note that I had to define the namespace that the ContentViews were located in and use that when defining the control in the xaml file:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:ScoreKeepersBoard.ContentViews"
x:Class="ScoreKeepersBoard.Views.HomePage"
Title="HomePage">
<VerticalStackLayout>
<Label
Text="Welcome to .NET MAUI Home Page Content Page"
VerticalOptions="Center"
HorizontalOptions="Center" />
<controls:HomePageOrientationViewLoader></controls:HomePageOrientationViewLoader>
</VerticalStackLayout>
</ContentPage>
Here is the code behind for the home page
namespace ScoreKeepersBoard.Views;
public partial class HomePage : ContentPage
{
public HomePage(HomeViewModel homeViewModel)
{
InitializeComponent();
}
}
and when the project runs on my iphone simulator in portrait mode:
You will see the second label shown says "Welcome to .NET MAUI portrait" which is the view from the portrait content view and when I switch to landscape:
You will see the second label shown says "Welcome to .NET MAUI landscape" which is the view from the landscape content view.
ISSUES
This works on my iPhone simulator but when I switch to my Android pixel 5 simulator and toggle my switch phone orientation it doesn't work and putting in line breaks the code defined in HomePageOrientationViewLoader is not triggered. NEW NOTE: I tried this on a physical Android phone and it is working so it must have just been the emulator.
I will need to use this for a non trivial example that has a view model that will be holding data on a sports game score, timing, etc. I guess I will just need to inject a singleton of the view model into each and they will just share and if the orientation switches the other Content View will load and the view model will bind to the appropriate controls?
The initial suggested code by FreakyAli had this check:
if (e.DisplayInfo.Orientation == DisplayOrientation.Landscape)
{
if (this.Content.GetType() is not typeof(HomePageLandscape))
{
this.Content = homePageLandscapeContentView;
}
}
but the part "typeof(HomePageLandscape) gives me an error and says a constant is expected.
Other than that the different views for different orientations is working and I thank FreakyAli mightily! I am sure I will figure out why the Android emulator is not triggering the orientation switch code, but suggestions would be awesome.
Ideally this is how i would handle such a scenario:
In my constructor, I would get the DisplayInfoChanged event which notifies me if this info changes and i would also assign my current ContentView based on the current Orientation:
DeviceDisplay.Current.MainDisplayInfoChanged += Current_MainDisplayInfoChanged;
this.Content = DeviceDisplay.Current.MainDisplayInfo.Orientation == DisplayOrientation.Portrait ? potraitView : landscapeView;
Here PortraitView is a ContentView that is the View I would display when my device is in Portrait and Vice Versa.
And then handle the runtime change of the orientation as follows:
private void Current_MainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
if(e.DisplayInfo.Orientation==DisplayOrientation.Landscape)
{
if(this.Content.GetType() is not typeof(LandscapeView))
{
this.Content = landscapeView;
}
}
else if (e.DisplayInfo.Orientation == DisplayOrientation.Portrait)
{
if (this.Content.GetType() is not typeof(PortraitView))
{
this.Content = portraitView;
}
}
else
{
//Whatever you would like to do if the orientation is unknown.
}
}
Hope this helps you!
The proper way to do this is through ContentViews where you have 2 ContentViews, one for portrait and one for landscape. You have another ContentView that is used to choose to load in either landscape or portrait depending on the orientation.
I created a tutorial that puts all of the pieces together:
https://codeshadowhand.com/net-maui-different-layouts-for-portrait-vs-landscape/
Thanks a million to FreakyAli for pointing me in the right direction!!!

Get native iOS system tab bar icons for TabbedPage on Xamarin.Forms

I am new to Xamarin.Forms and XAML. I am trying to get tab icons to display for ONLY IOS for the my different pages in my TabbedPage. I did a bit of search and I have come to know that UIKit has a reference to system icons available on IOS at UITabBarSystem. How can I make use of the elements in that enum without having to get those icons from the internet? The TabbedPage is the root with children pages that are ContentPages and ListView pages. So as you will see from the attached sample, I would like the "IconImageSource" property for FavouritesPage to get the image from the iOS UIKit. Is that possible?
<?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:views="clr-namespace:PhoneApp.Views"
x:Class="PhoneApp.Views.MainPage">
<TabbedPage.Title>
</TabbedPage.Title>
<TabbedPage.Children>
<views:FavouritesPage Title="Favourites" IconImageSource=""/>
<views:RecentsPage Title="Recents"/>
<views:ContactsPage Title="Contacts"/>
<views:KeypadPage Title="Keypad"/>
<views:VoicemailPage Title="Voicemail"/>
</TabbedPage.Children>
</TabbedPage>
I think I found the right solution for you. If you want to use native Api's on Xamarin controls, you can use custom renderer for them which are great! Here is the renderer for the TabedPage:
[assembly: ExportRenderer(typeof(MainPage), typeof(MyTabbedPageRenderer))]
namespace TestApp.iOS
{
public class MyTabbedPageRenderer : TabbedRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (TabBar?.Items == null) return;
//Setting the Icons
TabBar.Items[0].Image = GetTabIcon(UITabBarSystemItem.Search);
TabBar.Items[1].Image = GetTabIcon(UITabBarSystemItem.Downloads);
TabBar.Items[2].Image = GetTabIcon(UITabBarSystemItem.Bookmarks);
}
private UIImage GetTabIcon(UITabBarSystemItem systemItem)
{
//Convert UITabBarItem to UIImage
UITabBarItem item = new UITabBarItem(systemItem, 0);
return UIImage.FromImage(item.SelectedImage.CGImage, item.SelectedImage.CurrentScale, item.SelectedImage.Orientation);
}
}
}
I created a sample for you, which you can find here. If you have any questions, please ask!
Regards

Xamarin: make Rg Plugins Popup in Xaml?

I am getting all sorts of weird errors trying to instantiate a popup page in Xaml. This is the most vexing:
No property, bindable property, or event found for 'Content', or mismatching type between value and property.
Here's the page presenting the popup:
<?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 ="PopupPages.PopupBackingPage"
xmlns:popup ="clr-namespace:PopupPages"
BackgroundColor="Transparent">
<popup:PopupTest />
</ContentPage>
Here's its code-behind:
namespace PopupPages
{
public partial class PopupBackingPage : ContentPage
{
public PopupBackingPage()
{
InitializeComponent();
}
}
}
Here's the popup page itself, in xaml:
<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
x:Class="PopupPages.PopupTest">
</pages:PopupPage>
And here's the code-behind for the popup page itself:
namespace PopupPages
{
public partial class PopupTest : Rg.Plugins.Popup.Pages.PopupPage
{
public PopupTest()
{
InitializeComponent();
}
}
}
What's going on? What am I doing wrong? These are as dead simple as can be.
A Rg.Plugins.Popup is a page itself and can't be shown in a ContentPage. When wanting to display a popup page, display them using code like below:
await PopupNavigation.Instance.PushAsync(new PopupTest());
Put this code in the event that you were going to show the PopupBackingPage. A backing page is not needed and won't work with the Rg.Plugins.Popup pages.
Hopefully this helps!

Xamarin.Forms adding children to TabbedPage within OnBindingContextChanged

I'm trying to implement a TabbedPage using MvvmCross for my navigation. The problem is MvvmCross uses ViewModel first navigation and this doesn't seem to play well with the general approach one might take to add children to a TabbedPage; because I do not have access to a non-null ViewModel during page construction, but I do have access to it within OnBindingContextChanged.
Here's what I have so far...
DashboardPage.xaml:
<?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DashboardPage"
xmlns:local="clr-namespace:CoreUI;assembly=CoreUI"
SelectedItem="{Binding CurrentSection, Mode=TwoWay}">
</TabbedPage>
DashboardPage.xaml.cs:
public partial class DashboardPage : TabbedPage
{
public DashboardPage()
{
InitializeComponent();
}
protected override void OnBindingContextChanged()
{
var vm = (BindingContext as DashboardViewModel);
if (vm == null)
{
return;
}
ObservableCollection<MainMenuSection> sections = vm.MenuSections;
foreach (var section in sections)
{
MainMenuViewModel main_menu_vm = new MainMenuViewModel
{
Section = section
};
// Question 2:
// Going against the MvvmCross grain here by referring to other pages from within a page, as opposed to doing everything from a ViewModel. How do I get around this?
Children.Add(new MainMenuPage(main_menu_vm));
}
}
}
MainMenuPage.xaml (pay attention to the comments here):
<?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="MainMenuPage"
xmlns:local="clr-namespace:CoreUI;assembly=CoreUI"
Title="{Binding Title}" > <!-- The tabs that are displayed on Dashboard have the correct labels, so Binding appears to be working here. -->
<ContentPage.Content>
<StackLayout x:Name="Body" IsVisible="false">
<Label Text="{Binding Title}"/> <!-- Label doesn't get displayed, but does get displayed if Text is bound to something static, so Binding not quite working here. -->
</StackLayout>
</ContentPage.Content>
</ContentPage>
MainMenuPage.xaml.cs:
public partial class MainMenuPage : ContentPage
{
public MainMenuPage(MainMenuViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
protected override void OnBindingContextChanged()
{
Body.IsVisible = true;
}
}
The above MainMenuPage is a simplified version of what I have to illustrate my point, which is that I get a blank page for each tab within DashboardPage.
Question 1: Why are the tab pages blank?
Question 2: Refer to comment in DashboardPage.xaml.cs.
Why would you do this whole thing yourself? As you can see in the samples (https://github.com/MvvmCross/MvvmCross/tree/develop/TestProjects/Playground/Playground.Forms.UI/Pages) you can just decorate your view with a MvxTabbePagePresentation attribute and MvvmCross will handle the rest for you!
I would also advice to use the Mvx type pages to take advantage of lots of features.

How set tab 2 in a xamarin forms Tabbed Page as the default tab on startup

I have an app I am working on in xamarin forms it looks like this:
When the app loads the friends tab is the 1st tab to load how do I make it to where the snap tab is the 1st tab to load when the app starts up?
Here is my xaml code:
<?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:local="clr-namespace:AppName;assembly=AppName"
x:Class="AppName.HomePage">
<TabbedPage.Children>
<NavigationPage x:Name="Friends" Title="Friends" Icon="firendstab.png">
<x:Arguments>
<local:FriendPage />
</x:Arguments>
</NavigationPage >
<NavigationPage x:Name="Snap" Title="Snap" Icon="snaptab.png">>
<x:Arguments>
<local:CameraPage />
</x:Arguments>
</NavigationPage>
<NavigationPage x:Name="Notes" Title="Notes" Icon="notetab.png">
<x:Arguments>
<local:NotePage />
</x:Arguments>
</NavigationPage>
</TabbedPage.Children>
</TabbedPage>
heres my code behind:
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace AppName
{
public partial class HomePage : TabbedPage
{
public HomePage()
{
InitializeComponent();
}
}
}
I've searched google for the past 2 days so I thought it was time to ask!
You can access the enumerator of the TabbedPage's children and advance its position two times to get your "second tab". Assign that page as your CurrentPage:
public HomePage()
{
InitializeComponent();
var pages = Children.GetEnumerator();
pages.MoveNext(); // First page
pages.MoveNext(); // Second page
CurrentPage = pages.Current;
}
public HomePage()
{
InitializeComponent();
CurrentPage = Children[2];
}
I think you have to set "CurrentPage" property.
In code is something like
TabbedPage tp = new TabbedPage();
tp.Children.Add(new PageFriends());
tp.Children.Add(new PageSnap());
tp.Children.Add(new PageNotes());
tp.CurrentPage = tp.Children[1];
For me, what I did was this:
(this.Parent as TabbedPage).CurrentPage = (this.Parent as TabbedPage).Children[2];
because in my tabbed page, I added my pages like this
this.Children.Add(new Landing());
this.Children.Add(new Categories());
this.Children.Add(new Collections());
this.Children.Add(new Options());
The above code snippets, will lead me to the Collections Page.