5

Referencing code found at...Highlight a Route on a Map

They show...

var customMap = new CustomMap
{
    WidthRequest = App.ScreenWidth
};

App.ScreenWidth isn't available any longer. Has it been replaced with Application.Current.MainPage.Width?

John Livermore
  • 30,235
  • 44
  • 126
  • 216
  • Possible duplicate of [Get current screen width in xamarin forms](https://stackoverflow.com/questions/38891654/get-current-screen-width-in-xamarin-forms) – lucidbrot Mar 15 '19 at 14:33

3 Answers3

9

In that demo, App.ScreenWidth and App.ScreenHeight are static variables defined in the App class and assigned in the native projects:

iOS app project:

App.ScreenWidth = UIScreen.MainScreen.Bounds.Width;
App.ScreenHeight = UIScreen.MainScreen.Bounds.Height

Android app project:

App.ScreenWidth = (width - 0.5f) / density;
App.ScreenHeight = (height - 0.5f) / density;

Ref: https://github.com/xamarin/recipes/search?p=2&q=ScreenWidth&utf8=

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
7

Most simplest and accurate way to get device height & width in PCL:

using Xamarin.Forms;

namespace ABC
{
    public class MyPage : ContentPage
    {
        private double _width;
        private double _height;

        public MyPage()
        {
            Content = new Label 
            {
                WidthRequest = _width,
                Text = "Welcome to Xamarin.Forms!"
            };
        }

        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            _width = width;
            _height = height;
        }
    }
}
Jay Patel
  • 528
  • 8
  • 26
0

I believe the alternative, the OP suggested in the question, is the correct answer. look here

Update: One problem with this solution is that it will return -1 when MainPage did not appear yet. In this case, @SushiHangover solution is better.

Ashi
  • 806
  • 1
  • 11
  • 22