无法在Xamarin中设置SwitchCell的Binding
本文关键字:SwitchCell Binding 设置 Xamarin | 更新日期: 2023-09-27 17:51:20
我试图创建一个包含元素列表的SwitchCell。即使我发现如何做到这一点与一个普通的字符串列表感谢stackoverflow,我无法找出我做错了什么,当我试图绑定细胞属性到一个自制的结构体。
这是我的代码:
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不显示Name或布尔值
关于IsEnabledProperty - IsEnabled属性似乎有一个已知的错误,将在Xamarin中修复。Forms 2.3.0-pre1版本,这可能与您的情况有关:
https://bugzilla.xamarin.com/show_bug.cgi?id=25662关于Name属性——试着把你的FilterElement结构改成一个像这样带有properties和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"));
}
}
}
}
这样你就可以更新Types列表,它会自动更新ListView。
顺便说一下,如果你想根据ViewModels打开或关闭过滤器(而不是启用或禁用它),你需要为绑定使用OnProperty: https://developer.xamarin.com/api/field/Xamarin.Forms.SwitchCell.OnProperty/