清除 Xamarin 表单中的所有字段 [英] Clear all fields in Xamarin Forms

查看:32
本文介绍了清除 Xamarin 表单中的所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大约 25 个字段和一些下拉列表的表单,我想要一个干净的按钮来重置所有表单,有没有简单的方法来做到这一点?

I have a form with about 25 fields and some dropdowns too, I want to have a clean button that resets all the form, is there an easy way to do this?

推荐答案

如果您的控件通过双向绑定绑定到一个对象,您可以使用下面的代码迭代属性并清除值.

If your controls are bound to an object with two way binding you can iterate over the properties and clear the values using the code below.

    private async void btnClear_Clicked(object sender, EventArgs e)
    {
        MyData data = (MyData)this.BindingContext;
        await ClearProperties(data);
    }

    private async Task ClearProperties<T>(T instance)
    {
        await ClearProperties(typeof(T), instance);
    }

    private async Task ClearProperties(Type classType, object instance)
    {
        foreach (PropertyInfo property in classType.GetRuntimeProperties()) 
        {
            object value = null;
            try
            {
                value = property.GetValue(instance, null);
            }
            catch (Exception)
            {
                //Debug.WriteLine(ex.Message);
            }
            if (value != null && property.PropertyType != typeof(String))
                await ClearProperties(property.PropertyType, value);
            else if (value != null && (String)value != "")
                property.SetValue(instance, null);
        }
    }

这会循环遍历属性和它们的属性,如果它是一个字符串并且它不为空,它会将值设置为空.如果您绑定到字符串以外的其他内容,则可能需要对其进行一些修改.

This loops through the properties and their properties and if it is a String and it is not empty it will set the value to null. If you are binding to something other than a String you may have to modify it a bit.

这篇关于清除 Xamarin 表单中的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆