清除Xamarin Forms中的所有字段

时间:2017-03-31 13:32:02

标签: c# xamarin xamarin.forms

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

2 个答案:

答案 0 :(得分:2)

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

    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。如果你绑定的不是String,你可能需要稍微修改一下。

答案 1 :(得分:2)

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

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

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