多select列表视图

Multi-select Listview

这是我的列表视图,它应该包含来自我的 SQLite 数据库的活动列表:

<ListView SeparatorVisibility="None" x:Name="lstActivity" HasUnevenRows="True">
   <ListView.ItemTemplate>
       <DataTemplate>
           <ViewCell>
               <Frame StyleClass="lstframe" CornerRadius="0" BorderColor="Transparent" HasShadow="False">
                   <StackLayout StyleClass="lstContainer" VerticalOptions="CenterAndExpand">
                       <Grid>
                           <Label StyleClass="lstActivityName" Grid.Row="0" Grid.Column="0" Text="{Binding ActivityDescription}">
                               <Label.FontFamily>
                                    <OnPlatform x:TypeArguments="x:String">
                                        <On Platform="Android" Value="Poppins-Regular.otf#Poppins-Regular"/>
                                     </OnPlatform>
                                </Label.FontFamily>
                           </Label>
                           <Switch Grid.Row="0" Grid.Column="1" IsToggled="{Binding Selected}" />
                       </Grid>
                   </StackLayout>
               </Frame>
            </ViewCell>
       </DataTemplate>
    </ListView.ItemTemplate>
 </ListView>

这是我填充列表视图的方式,这将 return 至少五 (5) 个活动:

public void Get_Activities()
{
   try
   {
       var db = DependencyService.Get<ISQLiteDB>();
       var conn = db.GetConnection();

       var getActivity = conn.QueryAsync<ActivityTable>("SELECT * FROM tblActivity WHERE Deleted != '1' ORDER BY ActivityDescription");
       var resultCount = getActivity.Result.Count;

       if (resultCount > 0)
       {
           var result = getActivity.Result;
           lstActivity.ItemsSource = result;
           lstActivity.IsVisible = true;
       }
       else
       {
           lstActivity.IsVisible = false;
       }
    }
    catch (Exception ex)
    {
       //Crashes.TrackError(ex);
    }
}

已选项目绑定:

public class SelectData
{
   public bool Selected { get; set; }
}

点击获得 selected 项目:

private void BtnClose_Clicked(object sender, EventArgs e)
{
   foreach (var x in result)
   {
      if (x.Selected)
      {
         // do something with the selected items
      }
 }
    }

我发布了另一个关于多select 列表视图的问题我的问题是当我使用给我的答案时我不知道如何继续。我如何获取 selected 值,因为我会将 selected 值保存到我的数据库中?

您的 Switch 绑定到您模型的 Selected 属性。只需迭代(或使用 LINQ)即可获取所选项目。

// you need to maintain a reference to result
foreach(var x in result)
{
  if (x.Selected) 
  {
    // do something with the selected items
  }
}

LINQ

var selected = result.Where(x => x.Selected).ToList();

您还需要有一个 class 级别参考结果

// you will need to change this to reflect the actual type of result
List<MyClass> result;

public void Get_Activities()
{
    ...
    result = getActivity.Result;
    ...

对于多select Listview,我在我的博客中写了一个工作示例。希望这有帮助:https://androidwithashray.blogspot.com/2018/03/multiselect-list-view-using-xamarin.html?view=flipcard