Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gvsharma/da6afe9f1accbf91711805191d4d23b1 to your computer and use it in GitHub Desktop.
Save gvsharma/da6afe9f1accbf91711805191d4d23b1 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 ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment