首页 > 解决方案 > 需要 Xamarin CollectionView 行为再次运行

问题描述

我创建了一个行为来调整我的collectionview行,以防止 collectionview 调用它自己的滚动行为并防止最后一行之后的空间过多。

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>

类文件(不是后面的代码)

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;
            }
        }
    }

    ...
}

它适用于提供给的初始数据ItemsSource。但是,当我在视图模型中添加记录时ObservableCollection,该行为不会再次运行,从而导致出现滚动条。

如何强制CollectionView“重绘”自身以便再次运行行为?理想情况下,如果滚动条即将出现,并且公开一个方法来调用当前行的行为,则会触发一个事件。我在现实中找不到类似的东西。

标签: c#xamarin.formsbehaviorcollectionviewbindable

解决方案


推荐阅读