【问题标题】:Clear all fields in Xamarin Forms清除 Xamarin Forms 中的所有字段
【发布时间】:2017-03-31 13:32:01
【问题描述】:

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

【问题讨论】:

  • 这只是一个想法,不确定它是否有效,对于所有输入框,您可以将其绑定到字符串数组,例如条目 1 绑定到字符串 [1],条目 2 绑定到字符串[2] 等等。在清除按钮上,您可以清除应该对所有输入框进行排序的数组,我不确定下拉的任何简单方法。

标签: c# xamarin xamarin.forms


【解决方案1】:

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

    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。如果您绑定到 String 以外的其他内容,则可能需要对其进行一些修改。

【讨论】:

  • MyData 可以是 viewmodel 吗?
  • 我试过了,但我无法清除控件中存储的值。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2011-08-10
    • 2021-07-24
    • 1970-01-01
    相关资源
    最近更新 更多