如何使用 tapGesture 从应用程序中的多个标签中删除选定的标签 (Xamarin.Forms)

how to delete a selected label from multiple labels in an application using tapGesture (Xamarin.Forms)

我有一个按钮,每次单击它都会创建一个标签,假设我单击了 10 次,那么现在我创建了 10 个标签。如何删除我点击的随机标签?

PS: my labels are added to a stackLayout

我的应用程序的想法是创建一个待办事项列表。我有一个输入框和一个按钮。我在输入框中输入我想做的事情,然后单击按钮,然后创建一个标签,我刚刚在输入框中输入了该标签。当我完成某件事后,我想点击一个特定的标签并将其删除,这怎么可能。有帮助吗?

代码:

var entry = new Entry();
entry.Placeholder = "type here";
entry.BackgroundColor = Color.White;
entry.PlaceholderColor = Color.Gray;
var newButton = new Button { Text = "+", BackgroundColor = Color.Purple, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Button)), };
StackLayout stackLayout = new StackLayout();
stackLayout.Children.Add(entry);
stackLayout.Children.Add(newButton);
this.Content = stackLayout;

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += labelClick;
newButton.Clicked += (sender, args) => { label = new Label();
label.BackgroundColor = Color.White;
label.TextColor = Color.Black;
label.Text = entry.Text;
entry.Text = "";
stackLayout.Children.Add(label);
label.GestureRecognizers.Add(tapGestureRecognizer);    

嗯,我不知道你的代码是怎样的,这让回答你的问题有点困难,但我有一个想法:

如果您使用的是 MVVM 方法(我推荐),您可以使用此标签创建视图,将其绑定到具有待办事项数据(Id、名称、详细信息...)的 ViewModel,添加TapGesture 并在 ViewModel 中执行操作。

编辑:

这不是最好的方式,也不是我想要的方式。但这里有一个基于您的来源的解决方案:

    public MainPage()
    {
        var entry = new Entry();
        entry.Placeholder = "type here";
        entry.BackgroundColor = Color.White;
        entry.PlaceholderColor = Color.Gray;
        var newButton = new Button { Text = "+", BackgroundColor = Color.Purple, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Button)), };
        StackLayout stackLayout = new StackLayout();
        stackLayout.Children.Add(entry);
        stackLayout.Children.Add(newButton);
        this.Content = stackLayout;

        newButton.Clicked += (sender, args) =>
        {
            var label = new Label();
            label.BackgroundColor = Color.White;
            label.TextColor = Color.Black;
            label.Text = entry.Text;
            entry.Text = "";
            stackLayout.Children.Add(label);

            var tapGestureRecognizer = new TapGestureRecognizer();
            tapGestureRecognizer.Tapped += (sensder, e) => DeleteLabel(stackLayout, label);

            label.GestureRecognizers.Add(tapGestureRecognizer);
        };
    }

    void DeleteLabel(StackLayout stackLayout, Label label)
    {
        stackLayout.Children.Remove(label);
    }