I created a behavior that sizes my collectionview
rows to prevent the collectionview from invoking its own scrolling behavior and for preventing too much space after the last row.
XAML
<CollectionView ItemsSource="{Binding}" Margin="-55,0,0,0">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" ItemSpacing="0"/>
</CollectionView.ItemsLayout>
<CollectionView.Behaviors>
<core:CollectionViewRectangleVerticleHeightBehavior/>
</CollectionView.Behaviors>
<CollectionView.ItemTemplate>
<DataTemplate>
....
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Class file (not code behind)
public class CollectionViewRectangleVerticleHeightBehavior : 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)
{
if (!hasHeightChanged)
{
if (CollectionViewObject.BindingContext is Grouping<string,Estimate> grp)
{
CollectionViewObject.HeightRequest = (grp.Count * (32 + grp.Count == 1 ? 0 : 66 + 50));
hasHeightChanged = true;
}
}
}
...
}
It works fine with the initial data given to ItemsSource
. However, when I add records to the ObservableCollection
in the viewmodel, the behavior is not run again thereby causing a scroll bar to appear.
How do I force the CollectionView
to "redraw" itself so that the Behavior is run again? Ideally, an event would fire if the scrollbar is about to appear and a expose a method to invoke the behavior for the current row. I don't find anything like that in reality.