Xamarin.Forms 中ListView 修改选中效果
Posted devin_zhou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Xamarin.Forms 中ListView 修改选中效果相关的知识,希望对你有一定的参考价值。
在Xamarin.Forms中ListView是非常常用的控件之一,ListView有一个默认的选中效果,颜色和自己的App很不搭,怎么办呢?
1. 在很多时候,ListView在使用中不需要选中,更多情况下,只是点击一下而已,那么我们可以将其SelectMode设置为None。
<ListView BackgroundColor="Transparent" temsSource="{Binding PasswordList}" RowHeight="96" Margin="12" SelectionMode="None" ItemTapped="ListView_ItemTapped" SeparatorVisibility="None" SeparatorColor="Transparent"/>
2. 如果需要修改选中效果颜色怎么处理呢?
首先,自定义ExtendedViewCell继承ViewCell;
public class ExtendedViewCell : ViewCell { public static readonly BindableProperty SelectedBackgroundColorProperty = BindableProperty.Create("SelectedBackgroundColor", typeof(Color), typeof(ExtendedViewCell), Color.Default); public Color SelectedBackgroundColor { get { return (Color)GetValue(SelectedBackgroundColorProperty); } set { SetValue(SelectedBackgroundColorProperty, value); } } }
然后,根据各个平台为ExtendedViewCell提供一个Renderer(ExtendedViewCellRenderer);
[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))] namespace Deom.Droid.CustomRenderers { public class ExtendedViewCellRenderer : ViewCellRenderer { private Android.Views.View _cellCore; private Drawable _unselectedBackground; private bool _selected; protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context) { _cellCore = base.GetCellCore(item, convertView, parent, context); _selected = false; _unselectedBackground = _cellCore.Background; return _cellCore; } protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs args) { base.OnCellPropertyChanged(sender, args); if (args.PropertyName == "IsSelected") { _selected = !_selected; if (_selected) { var extendedViewCell = sender as ExtendedViewCell; _cellCore.SetBackgroundColor(extendedViewCell.SelectedBackgroundColor.ToAndroid()); } else { _cellCore.SetBackground(_unselectedBackground); } } } } }
ios:
[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))] namespace Demo.iOS.CustomRenderers { public class ExtendedViewCellRenderer : ViewCellRenderer { public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv) { var cell = base.GetCell(item, reusableCell, tv); var view = item as ExtendedViewCell; cell.SelectedBackgroundView = new UIView { BackgroundColor = view.SelectedBackgroundColor.ToUIColor(), }; return cell; } } }
这样就能修改选中效果啦。
以上是关于Xamarin.Forms 中ListView 修改选中效果的主要内容,如果未能解决你的问题,请参考以下文章
从按钮命令 xamarin.forms MVVM 获取 ListView
ListView 中突出显示的选定项 Xamarin.Forms
Android 上的 Xamarin.Forms ListView OutOfMemoryError 异常