简体   繁体   中英

Clear all fields in Xamarin Forms

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

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.

For example I have the same situation but all of entries and dropdowns are tied by a model through the BindingContext.

When clearing the form the only thing that is needed is to instantiate the model again and bind that to BindingContext.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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