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
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.