c# - 无法在 Xamarin 中设置 SwitchCell 的绑定(bind)

标签 c# xamarin xamarin.forms

我正在尝试创建一个带有元素列表的 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/

相关文章:

c# - 在方法签名中使用异步关键字返回 Web Api 端点中的任务

C# 从数据库中获取信息

c# - 使用 SignalR 时的 Azure 服务总线或 Azure Web 应用程序

javascript - 使用 c# - xamarin ios 最简单的用于 monotouch uiwebview 的 javascript 桥

c# - Xamarin Forms,如何将输入的日期从日期选择器转换为您选择的格式?

C# 暂停 foreach 循环,直到按下按钮

c# - 使用 NHibernate 进行慢速反射(额外调用 CodeAccessSecurityEngine)

c# - 统一 DLL 的 Monotouch.Dialog 替代方案

ios - iPad 在使用 Xamarin.Forms 启动时崩溃

mvvm - Xamarin.Forms 在 XAML 中将父属性与子属性绑定(bind)