如何绑定两个不同的项目

时间:2019-03-13 11:35:01

标签: c# xamarin

如何将一个列表中的两个不同项目彼此绑定,因此,删除一个项目时,它的绑定模式也将被删除。这个问题听起来很简单,但这些项目位于两个不同的列表中。

 public class MyClass{

 public StackLayout SavedHoursLayout = new StackLayout {};
 public Label RemoveHoursLabel;
 public TapGestureRecognizer RemoveTapped;
 public Grid HoursRemoveGrid;
 public Button AddHoursButton = new Button();
 public Label Correct = new Label{Text="Correct"};
 public list<Label> ItemsLayout = new list<Label>();

 public MyClass()
 {
      Content = new StackLayout
        {
            Children = { AddHoursButton,SavedHoursLayout }
        }
        AddHoursButton.Clicked+=AddHoursButton_Clicked;

 }
    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;
      ItemsLayout.Children.Add(Correct);

      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);
      }
     }

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

问题 现在,当我单击RemoveHourLabel时,我要删除Label Correct中与ItemsLayout相对应的RemovehoursGrid

NB ItemsLayout中已经有许多标签,因此每个Label Correct与其对应的RemoveHoursGrid都没有相同的索引。

1 个答案:

答案 0 :(得分:0)

解决方案:

您可以创建一个新的list<Label>来容纳标签,以使其具有与其对应的RemoveHoursGrid相同的索引。

首先,创建一个新列表,我们将其命名为tempItemsLayout

public List<Label> tempItemsLayout = new List<Label>();

然后在您的方法AddSavedHours中,也将正确的内容添加到tempItemsLayout:

public void AddSavedHours()
{    
    //...other codes

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

    //Add the correct to tempItemsLayout too
    tempItemsLayout.Add(Correct);

    //...other codes
}

然后在您的RemoveTapped_Tapped中,从tempItemsLayout和ItemsLayout中删除标签:

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);

        Label tempLabel = tempItemsLayout[position];

        //Remove the label from both tempItemsLayout and ItemsLayout
        tempItemsLayout.Remove(tempLabel);

        ItemsLayout.Remove(tempLabel);
}

尝试并让我知道它是否有效。