【发布时间】:2014-10-24 07:06:54
【问题描述】:
我正在使用 xamarin 表单设计一个跨平台应用程序。 每个页面/视图/表单都是从后面的代码设计的。现在我想读取用户使用的设备的高度和宽度。基于这些值,我想放置一些页眉和页脚。
【问题讨论】:
标签: xamarin xamarin.forms
我正在使用 xamarin 表单设计一个跨平台应用程序。 每个页面/视图/表单都是从后面的代码设计的。现在我想读取用户使用的设备的高度和宽度。基于这些值,我想放置一些页眉和页脚。
【问题讨论】:
标签: xamarin xamarin.forms
要在 Xamarin.Forms 解决方案中获取屏幕宽度(或高度),我通常会添加以下几行代码:
在共享代码中定义一个公共静态属性,最好在App.cs:
static public int ScreenWidth;
在FinishedLaunching开头的AppDelegate.cs中为iOS初始化它:
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
在MainActivity.cs 的OnCreate 中为Android 初始化它(如here 所述)
App.ScreenWidth = (int)(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
(除以密度,得到与设备无关的像素。)
我没有使用 Windows Phone,但应该有一个等效的命令。当然,获取屏幕高度也是类似的。
现在您可以在代码中的任何位置访问App.ScreenWidth。
【讨论】:
我在我的视图模型中执行此操作,效果很好。你可以在你的代码隐藏中做同样的事情。
public SomeViewModel
{
private double width;
private double Width
{
get { return width; }
set
{
width = value;
if (value != 0 && value != -1)
{
// device width found, set other properties
SetProperties();
}
}
}
void SetProperties()
{
// use value of Width however you need
}
public SomeViewModel()
{
Width = Application.Current.MainPage.Width;
var fireAndForget = Task.Run(GetWidthAsync);
}
public async Task GetWidthAsync()
{
while (Width == -1 || Width == 0)
{
await Task.Delay(TimeSpan.FromMilliseconds(1)).ConfigureAwait(false);
// MainPage is the page that is using this ViewModel
Width = Application.Current.MainPage.Width;
}
}
}
如果您想在表单的标签中显示宽度以使用绑定进行测试,请不要忘记将属性从私有更改为公共。
【讨论】: