有什么方法可以摆脱Xamarin表单列表视图中突出显示的项目的背景?

时间:2020-06-16 02:05:38

标签: listview xamarin xamarin.forms

我正在使用列表视图来呈现一些项目,但是我不希望任何背景。由于我使用的是SelectionMode =“ None”,因此tap事件不会标记该项目,但是灰色背景会出现并消失,这使您可以选择某些东西,而并非如此。我使用的是集合视图,但由于滚动时出现问题(抖动)而移至列表,因此移至集合不是解决方案。

我已经尝试过:

  • 触发-将背景颜色视图单元设置为无
  • 我更改了android样式: <item name="android:colorActivatedHighlight">@android:color/transparent</item>

我还没有在ios上测试它,但是我也必须从那里拿掉它。 有谁知道这是否可行以及如何实现?

1 个答案:

答案 0 :(得分:1)

您需要使用自定义渲染器摆脱灰色背景,让我向您展示代码:

一个简单的listView:

<StackLayout>
    <!-- Place new controls here -->
    <ListView SelectionMode="None"  ItemSelected="ListView_ItemSelected" ItemTapped="ListView_ItemTapped">
        <ListView.ItemsSource>
            <x:Array Type="{x:Type x:String}">
                <x:String>mono</x:String>
                <x:String>monodroid</x:String>
                <x:String>monotouch</x:String>
                <x:String>monorail</x:String>
                <x:String>monodevelop</x:String>
                <x:String>monotone</x:String>
                <x:String>monopoly</x:String>
                <x:String>monomodal</x:String>
                <x:String>mononucleosis</x:String>
            </x:Array>
        </ListView.ItemsSource>

        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding .}" />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>

    </ListView>
</StackLayout>

在Android项目中:

[assembly: ExportRenderer(typeof(Xamarin.Forms.ListView), typeof(DisplayOnlyListViewRenderer))]
namespace App277.Droid
{
    // DISABLES LISTVIEW ROW HIGHLIGHT
    [Obsolete]
    public class DisplayOnlyListViewRenderer : ListViewRenderer
    {

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

            if (Control != null)
            {
                Control.SetSelector(Android.Resource.Color.Transparent);
                Control.CacheColorHint = Android.Graphics.Color.Transparent;
            }
        }
    }
}

在iOS项目中:

[assembly: ExportRenderer(typeof(ViewCell), typeof(NativeViewCellRenderer))]
namespace App277.iOS
{
    public class NativeViewCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            var cell = base.GetCell(item, reusableCell, tv);

            // removes default selection style (gray background color on tapped event)
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;

            return cell;
        }
    }
}

我已经上传了演示here,随时可以问我任何问题。