【问题标题】:Get Device Properties using Xamarin Forms?使用 Xamarin 表单获取设备属性?
【发布时间】:2014-10-24 07:06:54
【问题描述】:

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

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

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

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

      static public int ScreenWidth;
      
    2. 在FinishedLaunching开头的AppDelegate.cs中为iOS初始化它:

      App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
      
    3. 在MainActivity.cs 的OnCreate 中为Android 初始化它(如here 所述)

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

      (除以密度,得到与设备无关的像素。)

    我没有使用 Windows Phone,但应该有一个等效的命令。当然,获取屏幕高度也是类似的。

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

    【讨论】:

    • 如果我们处于横向模式,我会添加宽度和高度之间的比较
    【解决方案2】:

    在 Xamarin Forms Labs here 中有一些类和示例可用于获取 设备 屏幕信息,如您所追求的。

    还有一些关于实现这一点并获取您需要here的Device对象的进一步说明。

    另外,如果您只想放置 Headers 和 Footers 那么为什么不使用内置的 Xamarin.Forms 控件来自动- 扩展控件和布局等,将根据用户设备的屏幕自动适应?

    我的印象是您希望采用 AbsoluteLayout 方法并自己指定值?如果是这样,真的没有必要。特别是对于布局的页眉和页脚?

    【讨论】:

      【解决方案3】:

      我在我的视图模型中执行此操作,效果很好。你可以在你的代码隐藏中做同样的事情。

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

      如果您想在表单的标签中显示宽度以使用绑定进行测试,请不要忘记将属性从私有更改为公共。

      【讨论】:

        猜你喜欢
        • 2018-10-18
        • 1970-01-01
        • 2018-10-31
        • 2015-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-18
        相关资源
        最近更新 更多