【问题标题】:Xamarin ListView SelectedIndex with duplicates in listXamarin ListView SelectedIndex,列表中有重复项
【发布时间】:2018-03-21 19:20:55
【问题描述】:

我已经搜索 SO 和 xamarin 论坛几个小时了,但还没有找到适合我的解决方案。我正在开发一个使用包含用户名列表的列表视图的 xamarin 应用程序。当我点击用户时,我想要一张地图平移到该用户的位置。没问题,除了当列表中有重复项时,我无法弄清楚如何从列表视图中获取用户的索引。

我尝试过使用这个:

var index = usersInGroup.IndexOf(MyListView.SelectedItem.ToString());

但这会在我的列表中找到第一个索引并且没有给出准确的结果。 我还尝试实施在 https://forums.xamarin.com/discussion/41504/get-position-and-item-number-of-list-itemXamarin Forms - Get position of item selected in Listview 以及其他一些来源中找到的解决方案。任何帮助深表感谢。以下是我目前用于列表视图的代码。仅供参考,这是我的第一个 xamarin 项目,我还在摸索中!

XAML:

<ListView x:Name="MyListView"
    HorizontalOptions="Center"
    ItemsSource="{Binding Items}"
    RowHeight="55"
    IsVisible="True"
    x:FieldModifier="public"                    
    CachingStrategy="RecycleElement"
      Grid.Row="3"
      Grid.ColumnSpan="2"
      BackgroundColor="White">

    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding .}" TextColor="Black" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

C#:

public GroupPage ()
{
    MyListView.ItemsSource = new ObservableCollection<string>(getUsers());
    MyListView.ItemSelected += listMemberSelected;
}

private void listMemberSelected(object sender, EventArgs e)
{
    //Doesn't work correctly when list contains duplicates
    var index = usersInGroup.IndexOf(MyListView.SelectedItem.ToString());
}

如果我遗漏了您认为重要的任何细节,请告诉我。

【问题讨论】:

  • 为什么列表中有重复项?我会考虑删除欺骗。
  • @RyanWilson 该列表由不唯一的用户名填充。用户可以添加他们想要的任何名称。我已经考虑过该解决方案,但这意味着重组数据库
  • 您不必重组数据库,只需更改返回用户的查询以仅选择 DISTINCT 名称
  • 为什么不能只使用 SelectedItem?为什么一定要有索引?
  • @RyanWilson 如果我这样做,我会从我的列表/地图中丢失共享相同用户名的用户

标签: c# listview xamarin


【解决方案1】:

不太理想,但我最终选择了一个在运行时动态生成控件的网格。我将整个内容放在滚动视图中以获得类似于列表视图的滚动,并且用户名位于填充行的按钮中,并且其样式与网格相匹配。

XAML

            <ScrollView Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
            <Grid x:Name="grdMembersGrid" RowSpacing="0" BackgroundColor="Black" Grid.Row="2" Grid.ColumnSpan="2">
            </Grid>
        </ScrollView>

C#:

将任何内容添加到网格中

                MyButton groupMembers = new MyButton();

            //Change text to username
            groupMembers.Text = usersInGroup[i];
            groupMembers.HorizontalOptions = LayoutOptions.FillAndExpand;
            groupMembers.VerticalOptions = LayoutOptions.Center;
            groupMembers.TextColor = Color.Black;
            groupMembers.BackgroundColor = Color.White;
            groupMembers.Clicked += GroupMembers_Clicked;

            grdMembersGrid.Children.Add(groupMembers, 0, userRowIndex);

获取按钮点击事件上的行:

        var row = (int)((BindableObject)sender).GetValue(Grid.RowProperty);

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2014-06-13
    • 2016-11-18
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2020-11-20
    • 2018-03-25
    相关资源
    最近更新 更多