多选Listview

问题描述 投票:0回答:2

这是我的列表视图,它应该包含来自我的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>

以下是我填充列表视图的方法,这将返回至少五(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; }
}

点击获取所选项目:

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

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

xamarin xamarin.forms xamarin.android xamarin.ios multi-select
2个回答
0
投票

你的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();

您还需要对结果进行类级别引用

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

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.