我正在尝试创建一个带有元素列表的 SwitchCell。 尽管我通过 stackoverflow 找到了如何使用普通字符串列表来做到这一点,但当我尝试将 Cell-Properties 绑定(bind)到自制结构时,我无法找出我做错了什么。
这是我的代码:
public class RestaurantFilter
{
public List<FilterElement> Types;
public RestaurantFilter(List<string> types)
{
Types = new List<FilterElement>();
foreach (string type in types)
Types.Add(new FilterElement { Name = type, Enabled = false });
}
}
public struct FilterElement
{
public string Name;
public bool Enabled;
}
public FilterPage()
{
List<string> l = new List<string>(new string[] { "greek", "italian", "bavarian" });
RestaurantFilter filter = new RestaurantFilter(l);
ListView types = new ListView();
types.ItemTemplate = new DataTemplate(() =>
{
var cell = new SwitchCell();
cell.SetBinding(SwitchCell.TextProperty, "Name");
cell.SetBinding(SwitchCell.IsEnabledProperty, "Enabled");
return cell;
});
types.ItemsSource = filter.Types;
Content = types;
}
但是应用程序中的 SwitchCell 不显示名称或 bool 值。
最佳答案
关于 IsEnabledProperty - IsEnabled 属性似乎存在一个已知错误,该错误将在 Xamarin.Forms 2.3.0-pre1 版本中修复,因此可能与您的情况有关:
https://bugzilla.xamarin.com/show_bug.cgi?id=25662
关于 Name 属性 - 尝试将 FilterElement 结构更改为具有属性和 PropertyChangedEventHandler 的类,如下所示,它将起作用:
public class FilterElement
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
private bool _enabled;
public bool Enabled
{
get { return _enabled; }
set
{
_enabled = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Enabled"));
}
}
}
}
这样您就可以更新类型列表,并且它会自动更新 ListView。
顺便说一句,如果您想根据 ViewModel 打开或关闭过滤器(而不是启用或禁用它),则需要使用 OnProperty 进行绑定(bind):
https://developer.xamarin.com/api/field/Xamarin.Forms.SwitchCell.OnProperty/
关于c# - 无法在 Xamarin 中设置 SwitchCell 的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38030732/