[英]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. 这将遍历属性及其属性,如果它是String且不为空,则将值设置为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. 例如,我有相同的情况,但是所有条目和下拉列表都通过BindingContext被模型绑定。
When clearing the form the only thing that is needed is to instantiate the model again and bind that to BindingContext. 清除表单时,唯一需要的是再次实例化模型并将其绑定到BindingContext。
private void ClearForm_OnClicked(object sender, EventArgs e)
{
BindingContext = new ViewModel();
_viewModel = (ViewModel)BindingContext;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.