Reputation: 954
I want to get the Grid width from my page, so I tried this:
public MemeBuilder()
{
InitializeComponent();
ColumnWidth = (MainGrid.Width - (8 * 5)) / 7;
....
But MainGrid.Width
returns -1.
Here is the xaml of the Grid:
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
.....
What am I doing wrong?
Upvotes: 1
Views: 403
Reputation: 16547
The best way to handle this is by using Xamarin.Essentials Device Display Information API
// Get Metrics
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
// Orientation (Landscape, Portrait, Square, Unknown)
var orientation = mainDisplayInfo.Orientation;
// Rotation (0, 90, 180, 270)
var rotation = mainDisplayInfo.Rotation;
// Width (in pixels)
var width = mainDisplayInfo.Width;
// Height (in pixels)
var height = mainDisplayInfo.Height;
// Screen density
var density = mainDisplayInfo.Density;
Now you can get the width by dividing the density something like:
var width = DeviceDisplay.MainDisplayInfo.Width / DeviceDisplay.MainDisplayInfo.Density;
Goodluck
Revert if you have questions
Upvotes: -2
Reputation: 1377
My mistake, you are using xamarin form.I think you are not getting the width because of the lifecycle like what @Peter B said. Either OnStart Event
protected override void OnStart()
{
ColumnWidth = (MainGrid.width- (8 * 5)) / 7;
}
or Page Appearing Event if your grid is in another page
protected async override void OnAppearing()
{
if(!isLoaded)
{
//Do API Calls
isLoaded=true;
}
}
Upvotes: 1
Reputation: 7449
You can subscribe to the SizeChanged
event and from there get the Width
:
private void MainGrid_SizeChanged(object sender, EventArgs e)
{
var grid = (Grid)sender;
var width = grid.Width;
}
Upvotes: 6