c# - 清除 Xamarin Forms 中的所有字段

标签 c# xamarin xamarin.forms

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

最佳答案

如果您的控件绑定(bind)到具有双向绑定(bind)的对象,您可以使用以下代码迭代属性并清除值。

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

这会遍历属性及其属性,如果它是一个字符串且不为空,它将把值设置为 null。如果您要绑定(bind)到 String 以外的其他内容,则可能需要对其进行一些修改。

关于c# - 清除 Xamarin Forms 中的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43142029/

相关文章:

c# - 如何使用收缩、toArray 和 fromArray 方法改进 System.Tuple

c# - 当我的 Xamarin Android 应用程序停止时,如何接收推送通知?

c# - 在没有设计器的情况下显示 DevExpress waitform 对话框

c# - 截取图像的一部分

c# - 程序集版本 ".001"变为 ".1"

android - Xamarin中的Build错误缺少youtube软件包

c# - 更改禁用按钮中的按钮文本颜色 (Xamarin.Forms)

ios - Xamarin 调试器无法连接到 iPad

android - Xamarin.Forms 中未调用 OnOptionsItemSelected

Release模式下的 Xamarin.Forms iOS 应用程序社区工具包 TouchEffect 命令未触发