2017-03-31 37 views
1

我有一個包含大約25個字段和一些下拉列表的表單,我想要一個乾淨的按鈕來重置所有表單,是否有一個簡單的方法來執行此操作?清除Xamarin表單中的所有字段

+0

這只是一個想法,不知道是否可行與否,所有的輸入框,你可以把它綁定到字符串,例如第1項的數組綁定到字符串[1],進入2串[2 ] 等等。在清除按鈕上,您可以清除應對所有輸入框進行排序的數組,我不確定是否有任何簡單的下拉方式。 –

回答

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

這循環遍歷屬性及其屬性,如果它是一個字符串,它不是空的,它將設置爲空值。如果你綁定到一個字符串以外的東西,你可能需要修改一下。

2

例如,我有相同的情況,但所有條目和下拉列表都通過BindingContext與模型綁定。

清除表單時,唯一需要的是再次實例化模型並將其綁定到BindingContext。

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