by tanyapodolskaia

Xamarin Tips: Change screen orientation with MessagingCenter

We can force the pages into Landscape mode at runtime as needed. UWP, iOS and Android require different approach, so here’s how we can handled it.

Xamarin.Forms:

public partial class MyAwesomePage : ContentPage
{
public MyAwesomePage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send(this, "SetLandscapeModeOn");
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Send(this, "SetLandscapeModeOff");
MessagingCenter.Unsubscribe<MyAwesomePage>(this, "SetLandscapeModeOff");
}
}

iOS:

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
MessagingCenter.Subscribe<MyAwesomePage>(this, "SetLandscapeModeOn", sender =>
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
});
MessagingCenter.Subscribe<MyAwesomePage>(this, "SetLandscapeModeOff", sender =>
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
});
return base.FinishedLaunching(app, options);
}
}

Android:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
MessagingCenter.Subscribe<MyAwesomePage>(this, "SetLandscapeModeOn", sender =>
{
RequestedOrientation = ScreenOrientation.Landscape;
});
MessagingCenter.Subscribe<MyAwesomePage>(this, "SetLandscapeModeOff", sender =>
{
RequestedOrientation = ScreenOrientation.Portrait;
});
}
}

UWP:

sealed partial class App : Application
{
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
Window.Current.Activate();
Xamarin.Forms.MessagingCenter.Subscribe<MyAwesomePage>(this, "SetLandscapeModeOn", sender =>
{
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
});
Xamarin.Forms.MessagingCenter.Subscribe<MyAwesomePage>(this, "SetLandscapeModeOff", sender =>
{
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;
});
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store