Xamarin Forms - Listview on selected item change a

2019-06-08 12:20发布

问题:

I found a error when you select a item all the children backgrounds are change for the same color.

In all elements, I put the property BackgroundColor. This only happened in the iOS

Follow the sample of the code:

XAML

<ListView
        x:Name="ListPainel"
        SeparatorColor="#d2d8e2"
        SeparatorVisibility="Default"
        Margin="0"
        ItemsSource="{Binding ListPainel_Source}"
        HasUnevenRows="true"
        RefreshCommand="{Binding ListPainel_RefreshCommand}"
        IsRefreshing="{Binding ListPainel_IsRefreshing}"

    >
    </ListView>

Part of ViewCell

        protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();

        dynamic temp = BindingContext;

        PainelDto painel = (PainelDto)temp;

        ...

        if(painel.HasDetalhes)
        {
            Button detalhes = new Button()
            {
                Text="VER DETALHES",
                FontSize = 12,
                TextColor = Color.FromHex("#4482ff"),
                HorizontalOptions = LayoutOptions.End,
                VerticalOptions = LayoutOptions.Start,
                HeightRequest = 20,
                WidthRequest = 120,
                BackgroundColor = Color.DeepPink
            };
            detalhes.SetBinding(
                Button.CommandProperty
                , new Binding(
                    "ViewDetalhesCommand"
                    , BindingMode.Default
                    , null
                    , null
                    , null
                    , _viewModelPainel
                )
            );
            box.Children.Add(detalhes);
        }

        ...

        View = box;
    }

Unselected Item

Selected Item

Some one know how to fix this?

回答1:

It is the default behavior when selecting cell in iOS.

We need a custom renderer for ViewCell to disable the effect.

Create a Class called NativeiOSCellRenderer in iOS project.

Code :

[assembly: ExportRenderer(typeof(ViewCell), typeof(NativeiOSCellRenderer))]
namespace FormsListViewSample.iOS
{
    class NativeiOSCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            UITableViewCell cell = base.GetCell(item, reusableCell, tv);
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;
            return cell;      
        }
    }
}