微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Xamarin Forms 清除所有条目

如何解决Xamarin Forms 清除所有条目

有没有办法清除 Xamarin.Forms 应用中的所有条目?我查看了此链接 here,但没有帮助。

解决方法

我使用了@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;
        }
    }

}
,

也许不是正确的方法,而是它如何在 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 = "";
        }

    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。