4
votes

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?

3

3 Answers

9
votes

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=

6
votes

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;
        }
    }
}
0
votes

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.