Get Device Properties using Xamarin Forms?

后端 未结 3 2029
梦谈多话
梦谈多话 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条回答
  •  情歌与酒
    2020-12-31 17:37

    I do this in my viewmodel and it works great. You could do the same in your code-behind.

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

    If you want to display Width in a label in your form for testing purposes using binding, don't forget to change the property from private to public.

提交回复
热议问题