Xamarin自定义布局系列——ListView的一个自定义实现

2017-03-15  本文已影响200人  cjw1115

在以前写UWP程序的时候,了解到在ListView或者ListBox这类的列表空间中,有一个叫做ItemsPannel的属性,它是所有列表中子元素实际的容器,如果要让列表进行横向排列,只需要在Xaml中如下编辑即可

    //UWP中用XAML大致实现如下
    ···
    <ListView.ItemsPannel>
        <StackPannel Orientation="Horizental"/>
    </ListView.ItemsPannel>
    ···

这种让列表元素横向排列实际是一个很常见的场景,但是在Xamarin.Forms中,并没有提供直接的实现方法,如果想要这种效果,有两种解决办法


怎么实现呢?

Xamarin.Forms的列表控件是直接利用Renderer实现的,没有提供类似ItemsPannel之类的属性,所以考虑直接自己实现一个列表控件。有以下几个点:

至此,先来给出这部分的代码,我们直接在构造函数中完成绝大多数操作

    ···
    private ScrollView _scrollView;
    private StackLayout itemsPanel = null;
    public StackLayout ItemsPanel
    {
        get { return this.itemsPanel; }
        set { this.itemsPanel = value; }
    }
    public ItemsControl()
    {
        this._scrollView = new ScrollView();
        this._scrollView.Orientation = Orientation;

        this.itemsPanel = new StackLayout() { Orientation = StackOrientation.Horizontal };//子元素水平排布的关键

        this.Content = this._scrollView;
        this._scrollView.Content = this.itemsPanel;
    }
    ···

子元素的容器是ItemsPannel,它实际是一个水平排布的StackLayout。想要在列表控件添加子元素,实际就是对该StackLayout的Children添加子元素。

考虑到列表控件中子元素的添加,就必须实现一个属性ItemsSource,是集合类型,并且为了支持数据绑定等,还需要让他是一个依赖属性,针对ItemsSource属性值自身的改变或者其集合中元素的添加删除等,都需要监听,并且将具体变化表现在ItemsControl中。实现该属性如下:

    ···
    public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create("ItemsSource", typeof(IEnumerable), typeof(ItemsControl), defaultBindingMode: BindingMode.OneWay, defaultValue: null, propertyChanged: OnItemsSourceChanged);
    
    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)this.GetValue(ItemsSourceProperty); }
        set { this.SetValue(ItemsSourceProperty, value); }
    }
    ···
    Static vid OnItemsSourceChanged(BindableObject sender,object oldValue,object newValue)
    {
        ···
    }
    ···

当为ItemsSource属性赋值之后,OnItemsSourceChanged方法被调用,在该方法中,需要干这么几件事儿:

OnItemsSourceChanged方法实现如下:

    public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create("ItemTemplate", typeof(DataTemplate), typeof(ItemsControl), defaultValue: default(DataTemplate));
    public DataTemplate ItemTemplate
    {
        get { return (DataTemplate)this.GetValue(ItemTemplateProperty); }
        set { this.SetValue(ItemTemplateProperty, value); }
    }

    static void OnItemsSourceChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var control = bindable as ItemsControl;
        if (control == null)
        {
            return;
        }
        //检测是否实现该接口,如果实现,就订阅该事件
        var oldCollection = oldValue as INotifyCollectionChanged;
        if (oldCollection != null)
        {
            oldCollection.CollectionChanged -= control.OnCollectionChanged;
        }

        if (newValue == null)
        {
            return;
        }

        control.ItemsPanel.Children.Clear();

        //遍历数据源中每个元素,为它创建View,并设置其BindingContext
        foreach (var item in (IEnumerable)newValue)
        {
            object content;
            content = control.ItemTemplate.CreateContent();
            View view;
            var cell = content as ViewCell;
            if (cell != null)
            {
                view = cell.View;
            }
            else
            {
                view = (View)content;
            }

            //元素点击相关事件
            view.GestureRecognizers.Add(control._tapGestureRecognizer);
            view.BindingContext = item;
            control.ItemsPanel.Children.Add(view);
        }

        

        var newCollection = newValue as INotifyCollectionChanged;
        if (newCollection != null)
        {
            newCollection.CollectionChanged += control.OnCollectionChanged;
        }
        control.SelectedItem = control.ItemsPanel.Children[control.SelectedIndex].BindingContext;

        //更新布局
        control.UpdateChildrenLayout();
        control.InvalidateLayout();
        
    }

CollectionChanged实现方法如下:

    private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
        {
            this.ItemsPanel.Children.RemoveAt(e.OldStartingIndex);
            this.UpdateChildrenLayout();
            this.InvalidateLayout();
        }

        if (e.NewItems == null)
        {
            return;
        }
        foreach (var item in e.NewItems)
        {
            var content = this.ItemTemplate.CreateContent();

            View view;
            var cell = content as ViewCell;
            if (cell != null)
            {
                view = cell.View;
            }
            else
            {
                view = (View)content;
            }
            if (!view.GestureRecognizers.Contains(this._tapGestureRecognizer))
            {
                view.GestureRecognizers.Add(this._tapGestureRecognizer);
            }
            view.BindingContext = item;
            this.ItemsPanel.Children.Insert(e.NewItems.IndexOf(item), view);
        }
        

        this.UpdateChildrenLayout();
        this.InvalidateLayout();
        
    }

到目前为止,已经实现ItemsControl控件大部分的内容了,还需要实现的有

怎么判断元素被选定呢?

当一个元素被点击后,认为它被选中了,所以需要监听列表中每一个元素的点击事件。

列表中每一个View被点击后,触发OnTapped事件,事件的发送者是该View本身

        //只定义一个TapGestureRecognizer,不需要为每一个元素都创建,只需要为每一个元素的GestureRecognizers集合添加该实例即可。
        TapGestureRecognizer _tapGestureRecognizer;

        //在构造函数中创建一个Tap事件的GestureRecognizer,并且订阅其Tapped事件
        public ItemsControl()
        {
            _tapGestureRecognizer = new TapGestureRecognizer();
            _tapGestureRecognizer.Tapped += OnTapped;
        }
        ···
        private void OnTapped(object sender, EventArgs e)
        {
            var view = (BindableObject)sender;
            this.SelectedItem = view.BindingContext;

        }
        ···
        static void OnItemsSourceChanged(BindableObject bindable, object oldValue, object newValue)
        {
            ···
            if (!view.GestureRecognizers.Contains(this._tapGestureRecognizer))
            {
                    view.GestureRecognizers.Add(this._tapGestureRecognizer);
            }
            ···
        }
        ···

一个基本的ItemsControl列表控件就完成了,至此,它的已经具备Xamarin.Forms提供的ListView的大致功能。不过还是有几点

具体代码和Demo看我的Github:

ItemsControl源码

上一篇 下一篇

猜你喜欢

热点阅读