Skip to content

Instantly share code, notes, and snippets.

@jedusei
Created May 16, 2022 20:30
Show Gist options
  • Save jedusei/c74df567822c46e70c9e1931be9bfbc1 to your computer and use it in GitHub Desktop.
Save jedusei/c74df567822c46e70c9e1931be9bfbc1 to your computer and use it in GitHub Desktop.
Set a minimum/maximum size for a view in Xamarin Forms
using System;
using Xamarin.Forms;
namespace App.Controls
{
public class SizeLimitView : ContentView
{
public static readonly BindableProperty MaximumWidthRequestProperty = BindableProperty.Create(nameof(MaximumWidthRequest), typeof(double), typeof(SizeLimitView), -1.0);
public static readonly BindableProperty MaximumHeightRequestProperty = BindableProperty.Create(nameof(MaximumHeightRequest), typeof(double), typeof(SizeLimitView), -1.0);
public double MaximumWidthRequest
{
get => (double)GetValue(MaximumWidthRequestProperty);
set => SetValue(MaximumWidthRequestProperty, value);
}
public double MaximumHeightRequest
{
get => (double)GetValue(MaximumHeightRequestProperty);
set => SetValue(MaximumHeightRequestProperty, value);
}
protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
{
SizeRequest sizeRequest = base.OnMeasure(widthConstraint, heightConstraint);
Size minSize = sizeRequest.Minimum;
Size requestedSize = sizeRequest.Request;
double minWidth = MinimumWidthRequest;
double minHeight = MinimumHeightRequest;
double maxWidth = MaximumWidthRequest;
double maxHeight = MaximumHeightRequest;
if (minWidth != -1)
{
minSize.Width = Math.Max(minWidth, minSize.Width);
requestedSize.Width = Math.Max(minWidth, requestedSize.Width);
}
if (minHeight != -1)
{
minSize.Height = Math.Max(minHeight, minSize.Height);
requestedSize.Height = Math.Max(minHeight, requestedSize.Height);
}
if (maxWidth != -1)
{
minSize.Width = Math.Min(maxWidth, minSize.Width);
requestedSize.Width = Math.Min(maxWidth, requestedSize.Width);
}
if (maxHeight != -1)
{
minSize.Height = Math.Min(maxHeight, minSize.Height);
requestedSize.Height = Math.Min(maxHeight, requestedSize.Height);
}
sizeRequest.Minimum = minSize;
sizeRequest.Request = requestedSize;
return sizeRequest;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment