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.
To get the screen width (or height) within a Xamarin.Forms solution, I usually add the following few lines of code:
Define a public static property in the shared code, preferably in App.cs
:
static public int ScreenWidth;
Initialize it for iOS at the beginning of FinishedLaunching
in AppDelegate.cs
:
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
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.)
I didn't work with Windows Phone, but there should be an equivalent command. And of course, getting the screen height works similarly.
Now you can access App.ScreenWidth
anywhere in your code.
In Xamarin Forms Labs here there are classes and examples for getting Device screen information like what you are after.
There are some further notes on implementing this and getting the Device object that you require here.
On a different note, if your only on about placing Headers and Footers then why not use the inbuilt Xamarin.Forms controls to auto-expand controls and layouts etc, that will adapt automatically based to screen of the user's device?
I get the impression that you are looking to go down an AbsoluteLayout approach and specify values yourself? If so, there really is no need. Especially for Headers and Footers of a Layout?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With