获取列表中子级的当前索引

时间:2019-03-07 11:46:19

标签: c# xamarin xamarin.forms

我有一个字符串列表,当我删除一个字符串时,字符串的索引不会改变,因此当我尝试删除另一个比我得到的索引高的字符串时,错误地指出了索引超出范围。

 public class MyClass{

     public StackLayout SavedHoursLayout = new StackLayout {};
     public Label RemoveHoursLabel;
     public TapGestureRecognizer RemoveTapped;
     public Grid HoursRemoveGrid;
     public Button AddHoursButton = new Button();

     public MyClass()
     {
          Content = new StackLayout
            {
                Children = { AddHoursButton,SavedHoursLayout }
            }
        AddHoursButton.Clicked+=AddHoursButton_Clicked;
         AddSavedHours();
     }
  public void AddSavedHours()
    {
        Label Time = new Label { };
        RemoveHoursLabel = new Label { Text="remove",TextColor=Color.Red,FontAttributes=FontAttributes.Italic};
        HoursRemoveGrid = new Grid();
        RemoveTapped = new TapGestureRecognizer();
        this.BindingContext = HoursRemoveGrid;

        HoursRemoveGrid.Children.Add(Time,0,0);
        HoursRemoveGrid.Children.Add(RemoveHoursLabel,1,0);
        SavedHoursLayout.Children.Add(HoursRemoveGrid);

        RemoveHoursLabel.GestureRecognizers.Add(RemoveTapped);
        RemoveTapped.Tapped += RemoveTapped_Tapped;


        void RemoveTapped_Tapped(object sender, EventArgs e)
        {
            int position = SavedHoursLayout.Children.IndexOf(HoursRemoveGrid);
            SavedHoursLayout.Children.RemoveAt(position);

        }
 }

    private void AddHoursButton_Clicked(object sender, System.EventArgs e)
    {
        AddSavedHours();
    }
  }

问题

在我将孩子添加到SavedHoursLayout后,单击RemoveHoursLabel,它将删除当前的RemoveHoursLabel,但是其余索引保持不变,因此当我单击另一个索引时删除为其分配了索引的子项,如果索引超出范围,我会收到一条错误消息

  

索引超出范围,不得为负或大于项目数。

因此,当从SavedHoursLayout更改中删除一个孩子时,如何将孩子的索引更新为当前索引。

1 个答案:

答案 0 :(得分:1)

使用发送方获取要删除的当前网格:

void RemoveTapped_Tapped(object sender, EventArgs e)
{
    var grid = (sender as Label).Parent as Grid;
    int position = SavedHoursLayout.Children.IndexOf(grid);
    SavedHoursLayout.Children.RemoveAt(position);
}