Xamarin 表单清除所有条目

Xamarin Forms Clear All Entries

有没有办法清除 Xamarin.Forms 应用中的所有条目?我检查了这个 link 但它没有帮助。

可能不是正确的方法,但可以举例说明它如何在 1 页上工作。

您可能想要更改它,但请了解它是如何工作的

<StackLayout>
    <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
        <Label Text="Clear All" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
    </Frame>

    <Entry x:Name="Nr1" />
    <Entry x:Name="Nr2" />
    <Entry x:Name="Nr3" />
    <Button Text="Clear" Clicked="Button_Clicked" />

</StackLayout>

还有 制作一个列表并为条目命名,我使用 Nr1、Nr2 和 Nr3,但仅作为示例。

public partial class MainPage : ContentPage
{
    List<Entry> entry = new List<Entry>();
    public MainPage()
    {
        InitializeComponent();
        entry.Clear();
        entry.Add(Nr1);
        entry.Add(Nr2);
        entry.Add(Nr3);

    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        foreach (var entry in entry)
        {

            entry.Text = "";
        }

    }
}

我使用了@Bassies 代码,修改为动态清除布局中的条目。因此,您不需要在代码后面添加引用。此方法将遍历每个项目和明文。因此,在比较@Bassies 方式时,这种动态方法将花费更多时间来处理。但这将是微不足道的时间,因为单个页面浏览量不会包含大量浏览量(如 10000 或更多)

 public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            var child = this.Content as Layout;
            if (child != null)
            {
                ProcessLayoutChildren(child);
            }
        }

        public void ProcessLayoutChildren(Layout child)
        {
            foreach (var item in child.Children)
            {
                var layout = item as Layout;
                if (layout != null)
                {
                    ProcessLayoutChildren(layout);
                }
                else
                {
                    ClearEntry(item);
                }
            }

            void ClearEntry(Element entryElement)
            {
                var entry = entryElement as Entry;
                if (entry != null)
                {
                    entry.Text = string.Empty;
                }
            }
        }
    }

我还没有测试过这个,但它应该可以工作

您可以遍历布局中的所有子视图并清除其中的条目。

如果您使用 XAML,请为您的布局命名,以便您可以在后端代码中访问它

<StackLayout x:Name="MyForm">
    <Label Text="Anything"/>
    <Entry />
    <Entry />
    <Entry />
    <Button Text="Clear" x:Name="Clear" Clicked="Clear_Clicked" />

</StackLayout>

然后在您的后端:

private void Clear_Clicked(object sender, EventArgs e)
{
    foreach (View view in MyForm.Children)
    {

        if(view is Entry)
        {
            (view as Entry).Text = String.Empty;
        }
    }

}