【问题标题】:Set ListView ItemSource Binding in Code Behind Xamarin Forms在 Xamarin 表单后面的代码中设置 ListView ItemSsource 绑定
【发布时间】:2017-09-12 10:38:12
【问题描述】:

我似乎无法得到这个问题的直接答案。 我试图在后面的代码中设置项目源。这在 Xaml 中很容易做到,但在后面的代码中似乎并不那么直接。

在我使用的代码后面:

Binding listbind = new Binding("routeLabels") {Source=this};

listviewofroutes.ItemsSource = SetBinding(ListView.ItemsSourceProperty, listbind);

这只会引发“无法将 void 转换为 System.Collections.IEnumerable”的错误,我也认为这是不正确的。

我正在尝试将其绑定到视图模型中的可观察集合。

视图模型:

private ObservableCollection<RouteInfo> _routelabels;
    public ObservableCollection<RouteInfo> routeLabels
    {
        get { return _routelabels; }
        set
        {
            if (Equals(value, _routelabels)) return;
            _routelabels = value;
            OnPropertyChanged(nameof(routeLabels));

        }
    }

在 Xaml 中设置绑定时,此绑定可以正常工作。 问题不是可观察的集合问题是我不知道如何在后面的代码中设置绑定。

总结:

我需要知道怎么做(itemsource 绑定):

<ListView x:Name="listviewofroutes" ItemsSource="{Binding routeLabels}">


</ListView>

在后面的代码中。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# xaml xamarin.forms


    【解决方案1】:

    要以编程方式在控件上设置绑定,您必须将其作为参数传递给扩展方法。参考链接:extension methods,或member method

    例如,试试:

    listviewofroutes.SetBinding(ListView.ItemsSourceProperty, "routeLabels")
    //Or, 
    listviewofroutes.SetBinding(ListView.ItemsSourceProperty, new Binding("routeLabels")) 
    

    这将路径设置为“routeLabels”和控件的BindingContext(即视图模型)之间的绑定。

    此外,建议根据 C# 属性的标准命名策略将“routeLabels”更改为“RouteLabels”。

    【讨论】:

    • 我会试试这个。一分钟。
    猜你喜欢
    • 2012-10-14
    • 2017-08-05
    • 2011-12-27
    • 2019-11-24
    • 1970-01-01
    • 2012-03-30
    • 2016-10-10
    • 2016-05-16
    • 1970-01-01
    相关资源
    最近更新 更多