使用 Xamarin Forms 获取设备属性? [英] Get Device Properties using Xamarin Forms?

查看:29
本文介绍了使用 Xamarin Forms 获取设备属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个使用 xamarin 表单的跨平台应用程序.每个页面/视图/表单都是从背后的代码设计的.现在我想读取用户使用的设备的高度和宽度.根据这些值,我想放置一些页眉和页脚.

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. based on those values, i want to place some header and footers.

推荐答案

为了在 Xamarin.Forms 解决方案中获取屏幕宽度(或高度),我通常添加以下几行代码:

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

  1. 在共享代码中定义一个公共静态属性,最好在App.cs中:

static public int ScreenWidth;

  • AppDelegate.cs中的FinishedLaunching开头为iOS初始化:

  • Initialize it for iOS at the beginning of FinishedLaunching in AppDelegate.cs:

    App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
    

  • MainActivity.csOnCreate 中为 Android 初始化它(如这里)

  • 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.)

    我没有使用 Windows Phone,但应该有一个等效的命令.当然,获取屏幕高度的工作原理类似.

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

    现在您可以在代码的任何位置访问 App.ScreenWidth.

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

    这篇关于使用 Xamarin Forms 获取设备属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆