user10200885
user10200885

Reputation:

How to do a multi select list-view and get the selected item?

I have a list view with car brands. I am doing a basic survey app that the user needs to select all that applies. So far I can only do is to get one selected item based on the tutorial online. Is there a way to have a multi-select list view and get the value? or What are the other things I can do to achieve this?

var listView = new ListView();
listView.ItemsSource = new string[]
{
  "Honda",
  "Toyota",
  "Ford",
  "Tesla"
};

Upvotes: 2

Views: 3550

Answers (2)

FreakyAli
FreakyAli

Reputation: 16572

The First thing you need to do is make a generic something as below:

public class SelectableData<T> 
{ 
  public T Data { get; set; }
  public bool Selected { get; set; } 
}

Next, you will want to create the ListView, that shows the data and the Switch. In this example, my Data, just has Name and Description inside it. The wrapper, then contains the Selected Boolean.

<ListView ItemsSource="{Binding DataList}" Margin="20">
<ListView.ItemTemplate> 
    <DataTemplate> 
        <ViewCell> 
            <Grid Margin="0,0,0,10"> 
                <Grid.ColumnDefinitions> 
                    <ColumnDefinition Width="*" /> 
                    <ColumnDefinition Width="Auto" /> 
                </Grid.ColumnDefinitions> 
                <StackLayout VerticalOptions="CenterAndExpand"> 
                    <Label Text="{Binding Data.Name}"  /> 
                    <Label Text="{Binding Data.Description}" FontSize="10" /> 
                </StackLayout> 
                <Switch IsToggled="{Binding Selected}" Grid.Column="1" /> 
            </Grid> 
        </ViewCell> 
    </DataTemplate> 
</ListView.ItemTemplate>
</ListView>

Then bind the ListView with something like this:

public ObservableCollection<SelectableData<ExampleData>> DataList { get; set; }

Where ExampleData is something like:

 public class ExampleData
{
  public string Name { get; set; }
  public string Description { get; set; }
}

To get the selected item iterate through the DataList using a for each loop and check the Selected Property something like this:

foreach(var item in DataList)
{
   item.Selected // true if selected else false.
}

Upvotes: 2

lawiluk
lawiluk

Reputation: 599

Firstly, don't assign an array of strings to ItemsSource. Bind your ItemsSource to ObservableCollection. When you do that the list will be updated whenever you change the collection. For more info take a look here.

Secondly, out of the box Xamarin.Forms doesn't provide you with an option to select multiple items. Though, you can do that following these instructions

Upvotes: 1

Related Questions