LoginSignup
3
5

More than 5 years have passed since last update.

Xamarin.Forms.WPFでListViewのViewCellをウインドウ幅に追従させる

Last updated at Posted at 2019-03-17

現状のXamarin.Forms.WPFのListViewのViewCellは、ウインドウ幅を変えても、大きさが変わりません。そこで、カスタムレンダラーで、ちゃんとウインドウ幅に追従するようにしてみました。

実装

.NET Standard

namespace CustomListView.Controls
{
    public class CustomListView : ListView
    {
        public CustomListView() : base()
        {
        }

        public CustomListView(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy)
        {
        }
    }
}

WPF

[assembly: ExportRenderer(typeof(CustomListView.Controls.CustomListView), typeof(CustomListView.WPF.Renderers.CustomListViewRenderer))]
namespace CustomListView.WPF.Renderers
{
    public class CustomListViewRenderer : ListViewRenderer
    {
        protected override void UpdateWidth()
        {
            base.UpdateWidth();

            if (Control != null && Control.ItemsSource != null)
            {
                foreach (var item in Control.ItemsSource)
                {
                    if (item is ViewCell viewCell)
                    {
                        var element = Platform.GetRenderer(viewCell.View)?.GetNativeElement();
                        if (element != null)
                        {
                            element.Width = Control.Width - 36;
                        }
                    }
                }
            }
        }
    }
}

ウインドウ幅が変わった時に、UpdateWidthが呼ばれるので、そこで、全ViewCellの幅を変更するようにしています。

結果

通常

listview.gif

CustomListView

customlistview.gif

ソース

全体のソースはこちらです。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5