繁体   English   中英

清除Xamarin表单中的所有字段

[英]Clear all fields in Xamarin Forms

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

如果控件通过两种方式绑定到对象,则可以遍历属性并使用下面的代码清除值。

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

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

例如,我有相同的情况,但是所有条目和下拉列表都通过BindingContext被模型绑定。

清除表单时,唯一需要的是再次实例化模型并将其绑定到BindingContext。

    private void ClearForm_OnClicked(object sender, EventArgs e)
    {
        BindingContext = new ViewModel();
        _viewModel = (ViewModel)BindingContext;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM