XamaWIN – Override ListView Select State using Effects

Xamawin • zam-ah win | noun
A quick, easy to implement enhancement for a Xamarin App that improves performance, appearance, or functionality


ListView in Xamarin.Forms is a spectacular way to render repeatable elements of similar format for the user. A typical application would involve some sort of user interaction, such a selecting a single element and then navigating to a new view.

In this post, we will explore a means of interacting with an element on an individual ListViewItem instead. While this is simple in UWP using SelectionMode Xamarin.Forms doesn’t expose similar functionality out of the box (yet!), because of the discrete way each platform handles lists. Fortunately, thanks to our good friend, PlatformEffect, achieving this functionality is a snap!

Let’s start with the effect in our iOS project:

[assembly: ResolutionGroupName("MyEffects")]
[assembly: ExportEffect(typeof(ListViewHighlightEffect), nameof(ListViewHighlightEffect))]
namespace Effects.iOS.Effects
{
    public class ListViewHighlightEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var listView = (UIKit.UITableView)Control;

            listView.AllowsSelection = false;
        }

        protected override void OnDetached()
        {

        }
    }
}

When we turn our attention to Android, you’ll notice it follows similarly:

[assembly: ResolutionGroupName("MyEffects")]
[assembly: ExportEffect(typeof(ListViewHighlightEffect), nameof(ListViewHighlightEffect))]
namespace Effects.Droid.Effects
{
    public class ListViewHighlightEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var listView = (Android.Widget.ListView)Control;

            listView.ChoiceMode = ChoiceMode.None;
        }

        protected override void OnDetached()
        {
            
        }
    }
}

For good measure, we can make highlighting transparent, as in this previous post using styles.xml

Now, we simply apply the effect in the code behind for our intended view, like so:

ListView_Demo.Effects.Add(Effect.Resolve($"MyEffects.ListViewHighlightEffect"));

The result is a much cleaner experience when scrolling through our view. Check out the before and after on iOS below:

2 thoughts on “XamaWIN – Override ListView Select State using Effects

Leave a comment