无法使用可见属性和mvvm绑定在列表视图中隐藏行/缩小列表视图项

时间:2019-05-23 22:57:27

标签: listview xamarin mvvm xamarin.android

我有一个切换按钮和一个列表(其中包含行或标签,网格中的堆栈布局)。 Toggle(Switch)和List View在Xaml文件中声明,其中list的数据单元以编程方式在cs文件中生成。我需要隐藏/显示基于切换开关的列表内部的堆栈布局。

我已经实现了这一点,方法是在列表的对象中创建一个布尔字段,并在启用切换功能时将其分配为true。并在stacklayout的ISvisiblePraperty中使用此字段

stacklayout.SetBinding(IsVisibleProperty, new Binding("SubItemSectionVisible", BindingMode.Default, new BooleanConverterForSubItem()));

现在,根据切换,我可以看到stacklayout内的文本隐藏并可见,但是列表项的大小没有缩小。 我必须滚动一次列表才能看到listview项缩小或扩展。 单击切换后,有没有办法实现这种缩小?

此问题仅在iOS中存在,在android中按预期工作正常。

谢谢。

1 个答案:

答案 0 :(得分:0)

对于Xamarin Forms iOS,这并不是什么新鲜事物。它已经存在了一段时间,并且与您完全诚实,我不确定Xamarin是否提供了正确的(性能)解决方案,但是如果确实存在,请忽略以下内容。 :-)

这已经存在了一段时间...

https://developer.xamarin.com/samples/xamarin-forms/UserInterface/ListView/DynamicUnevenListCells/

...但始终是一种非常糟糕的方法。值得一试,否则,我将通过创建自定义渲染器来克服它。

自定义控件

using System;
using Xamarin.Forms;

namespace YourApplication.Controls
{
    public class CustomListView : ListView
    {
        public event EventHandler<int> ItemHeightChangedEvent;

        public void ItemHeightChanged(int index)
        {
            ItemHeightChangedEvent?.Invoke(this, index);
        }
    }
}

自定义iOS渲染器

using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using UIKit;
using System.ComponentModel;
using YourApplication.Controls;
using Foundation;

[assembly: ExportRenderer(typeof(CustomListView), typeof(YourApplication.iOS.CustomListViewRenderer))]

namespace YourApplication.iOS
{
    public class CustomListViewRenderer : ListViewRenderer
    {
        private CustomListView _formsListView;

        protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
        {
            base.OnElementChanged(e);

            _formsListView = Element as CustomListView;

            if (_formsListView == null)
                return;

            _formsListView.ItemHeightChangedEvent += async (object sender, int index) =>
            {
                Control.ReloadRows(new NSIndexPath[] { NSIndexPath.FromRowSection(index, 0) }, UITableViewRowAnimation.Automatic);
            };
        }
    }
}

XAML

<localControls:CustomListView ItemsSource="{Binding Source}" ... >

您需要阅读自定义渲染器的创建方法(如果您还不熟悉如何使用它们),然后要做的就是在该项目上调用ItemHeightChanged方法当单元格改变时。

性能可能令人怀疑(因此为什么只攻击已更改的物品),但对我有用。

我希望这很有道理,希望对您有所帮助。