我有一个包含大约 25 个字段和一些下拉菜单的表单,我想要一个可以重置所有表单的干净按钮,有没有简单的方法可以做到这一点?
最佳答案
如果您的控件绑定(bind)到具有双向绑定(bind)的对象,您可以使用以下代码迭代属性并清除值。
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。如果您要绑定(bind)到 String 以外的其他内容,则可能需要对其进行一些修改。
关于c# - 清除 Xamarin Forms 中的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43142029/