0

It's really this simple. I want the Width of my entire screen in Xamarin.Forms. You'd think that when I call ParentView.Width, it will return for me the width of the parent view. Instead, it returns me an exception. "Object reference not an instance of an object."

What do I do to get the Width of a parent view so that I can manipulate a child element based on that width. For instance:

int xPos = this.Width*0.5;
//or 
int xPos = ParentView.Width*0.5;
adamsloma
  • 179
  • 1
  • 1
  • 8

1 Answers1

0

If you need the width of the screen, you can use

on Android:

Resources.DisplayMetrics.WidthPixels

or (more likely):

Resources.DisplayMetrics.WidthPixels / 
            Resources.DisplayMetrics.Density

if you want it in dip and not in pixels. (all Xamarin.Forms controls use dip for their WidthRequest and HeightRequest).

on iOS:

UIScreen.MainScreen.Bounds.Width

You can also make an interface and use DependencyService to return the width for each platform to your shared project

Grisha
  • 713
  • 5
  • 13
  • You could also find working implementation in Xamarin-Forms-Labs project https://github.com/XLabs/Xamarin-Forms-Labs/wiki/Device (see http://stackoverflow.com/a/26504582/5064986) – Daniel Luberda Jul 09 '15 at 16:46