Skip to content

Instantly share code, notes, and snippets.

@mamift
Last active November 3, 2020 22:58
Show Gist options
  • Select an option

  • Save mamift/5fecb7eda9dcec1fc9f183528a107e39 to your computer and use it in GitHub Desktop.

Select an option

Save mamift/5fecb7eda9dcec1fc9f183528a107e39 to your computer and use it in GitHub Desktop.
A custom behaviour for Xamarin's CollectionView control that modulates its height based on how many items it's showing. Taken from https://forums.xamarin.com/discussion/158425/collectionview-included-additional-space-at-the-bottom. Addresses: https://github.com/xamarin/Xamarin.Forms/issues/6497
public class CollectionViewHeightBehavior : Behavior<CollectionView>
{
bool hasHeightChanged = false;
public CollectionView CollectionViewObject
{
get;
private set;
}
protected override void OnAttachedTo(CollectionView bindable)
{
base.OnAttachedTo(bindable);
CollectionViewObject = bindable;
bindable.BindingContextChanged += Bindable_BindingContextChanged;
bindable.SizeChanged += Bindable_SizeChanged;
}
private void Bindable_SizeChanged(object sender, EventArgs e)
{
var collectionHeight = CollectionViewObject.Height;
if (CollectionViewObject.Height > 0 && !hasHeightChanged)
{
CollectionViewObject.HeightRequest = (collectionHeight / 2) + 20;
hasHeightChanged = true;
}
}
private void Bindable_BindingContextChanged(object sender, EventArgs e)
{
OnBindingContextChanged();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
BindingContext = CollectionViewObject.BindingContext;
}
protected override void OnDetachingFrom(CollectionView bindable)
{
base.OnDetachingFrom(bindable);
bindable.BindingContextChanged -= Bindable_BindingContextChanged;
bindable.SizeChanged -= Bindable_SizeChanged;
}
}
/* To consume in XAML:
<CollectionView.Behaviors>
<behavior:CollectionViewHightBehavior/>
</CollectionView.Behaviors>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment