Created
May 16, 2022 20:30
-
-
Save jedusei/c74df567822c46e70c9e1931be9bfbc1 to your computer and use it in GitHub Desktop.
Set a minimum/maximum size for a view in Xamarin Forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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