使用Xamarin表单获取设备属性? [英] Get Device Properties using 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:
-
在共享代码中(最好在
App.cs
中)定义公共静态属性:
Define a public static property in the shared code, preferably in
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.cs
的OnCreate
中将其初始化为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表单获取设备属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!