Get Device Properties using Xamarin Forms?

后端 未结 3 2026
梦谈多话
梦谈多话 2020-12-31 17:00

i\'m designing a cross platform app using xamarin forms. every page/view/Form designed from code behind. now i want to read Height and Width of the device used by user. base

3条回答
  •  梦毁少年i
    2020-12-31 17:11

    To get the screen width (or height) within a Xamarin.Forms solution, I usually add the following few lines of code:

    1. Define a public static property in the shared code, preferably in App.cs:

      static public int ScreenWidth;
      
    2. Initialize it for iOS at the beginning of FinishedLaunching in AppDelegate.cs:

      App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
      
    3. Initialize it for Android in OnCreate of MainActivity.cs (as described here)

      App.ScreenWidth = (int)(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
      

      (By dividing by the density this yields device independent pixels.)

    I didn't work with Windows Phone, but there should be an equivalent command. And of course, getting the screen height works similarly.

    Now you can access App.ScreenWidth anywhere in your code.

提交回复
热议问题