问题描述
我正在尝试创建带有元素列表的SwitchCell.尽管由于stackoverflow我找到了使用普通字符串列表的方法,但是当我尝试将Cell-Properties绑定到自制结构时,我还是找不到我做错的事情.
I am trying to create a SwitchCell with a list of Elements.Eventhough I found out how to do that with a plain string-List thanks to stackoverflow I can't find out what I'm doing wrong when I try to bind the Cell-Properties to a self-made struct.
这是我的代码:
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不会显示名称或布尔值.
But the SwitchCell's in the Application do not show the Name or the Boolean.
推荐答案
关于IsEnabledProperty-似乎存在IsEnabled属性的已知错误,该错误将在Xamarin.Forms 2.3.0-pre1版本中修复.与您的情况有关:
About the IsEnabledProperty - there seem to be a knonw bug with the IsEnabled property that will be fixed in the Xamarin.Forms 2.3.0-pre1 release so that might be related to your case:
https://bugzilla.xamarin.com/show_bug.cgi?id=25662
关于Name属性-尝试将您的FilterElement结构更改为具有如下属性和PropertyChangedEventHandler的类,它将起作用:
About the Name property - try changing your FilterElement struct to a class with properties and PropertyChangedEventHandler like this and it will work:
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.
That way you will be able to update the Types list and it will automatically update the ListView.
顺便说一句,如果要基于ViewModel打开或关闭过滤器(不启用或禁用过滤器),则需要使用OnProperty进行绑定:
By the way, if you want to turn the filter on or off based on your ViewModels (not enable or disable it), you need to use the OnProperty for the binding:
https://developer.xamarin.com/api/field/Xamarin.Forms.SwitchCell.OnProperty/
这篇关于无法在Xamarin中设置SwitchCell的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!