Skip to content

Instantly share code, notes, and snippets.

@glennstephens
Created December 15, 2015 04:01
Show Gist options
  • Save glennstephens/76e7e347ca6c19d4ef15 to your computer and use it in GitHub Desktop.
Save glennstephens/76e7e347ca6c19d4ef15 to your computer and use it in GitHub Desktop.
Multi-select in Xamarin in Forms
using System;
using System.Linq;
using Xamarin.Forms;
using System.Collections.Generic;
using System.ComponentModel;
namespace SampleApp
{
// Inherit from this page to get a multi-select option in XF
public class SelectMultipleBasePage<T> : ContentPage
{
public class WrappedSelection<T> : INotifyPropertyChanged
{
public T Item { get; set; }
bool isSelected = false;
public bool IsSelected {
get {
return isSelected;
}
set
{
if (isSelected != value) {
isSelected = value;
PropertyChanged (this, new PropertyChangedEventArgs (nameof (IsSelected)));
}
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate {};
}
public class WrappedItemSelectionTemplate : ViewCell
{
public WrappedItemSelectionTemplate() : base ()
{
Label name = new Label();
name.SetBinding(Label.TextProperty, new Binding("Item.Name"));
Switch mainSwitch = new Switch();
mainSwitch.SetBinding(Switch.IsToggledProperty, new Binding("IsSelected"));
RelativeLayout layout = new RelativeLayout();
layout.Children.Add (name,
Constraint.Constant (5),
Constraint.Constant (5),
Constraint.RelativeToParent (p => p.Width - 60),
Constraint.RelativeToParent (p => p.Height - 10)
);
layout.Children.Add (mainSwitch,
Constraint.RelativeToParent (p => p.Width - 55),
Constraint.Constant (5),
Constraint.Constant (50),
Constraint.RelativeToParent (p => p.Height - 10)
);
View = layout;
}
}
public List<WrappedSelection<T>> WrappedItems = new List<WrappedSelection<T>>();
public SelectMultipleBasePage(List<T> items)
{
WrappedItems = items.Select (item => new WrappedSelection<T> () { Item = item, IsSelected = false }).ToList ();
ListView mainList = new ListView () {
ItemsSource = WrappedItems,
ItemTemplate = new DataTemplate (typeof(WrappedItemSelectionTemplate))
};
Content = mainList;
ToolbarItems.Add (new ToolbarItem ("All", null, SelectAll, ToolbarItemOrder.Primary));
ToolbarItems.Add (new ToolbarItem ("None", null, SelectNone, ToolbarItemOrder.Primary));
}
void SelectAll ()
{
foreach (var wi in WrappedItems)
wi.IsSelected = true;
}
void SelectNone ()
{
foreach (var wi in WrappedItems)
wi.IsSelected = false;
}
public List<T> GetSelection()
{
return WrappedItems.Where (item => item.IsSelected).Select (wrappedItem => wrappedItem.Item).ToList ();
}
}
}
@pravinnerkar
Copy link

I still see the issue related to row size on Windows platform , Was the issue fixed in latest version ?

@sclarson
Copy link

As a gist this doesn't have a license (that I'm aware of anyway), would you be willing to say that this is MIT or similarly licensed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment