简体   繁体   English

在Xamarin表单背后的代码中设置ListView ItemSource绑定

[英]Set ListView ItemSource Binding in Code Behind Xamarin Forms

I can't seem to get a straight answer for this problem. 对于这个问题,我似乎无法获得直接的答案。 Im trying to set the item source in the code behind. 我试图在后面的代码中设置项目来源。 This is easy to do in the Xaml but seems to be not so straight forward in the code behind. 这在Xaml中很容易做到,但是在后面的代码中似乎并不那么简单。

In the code behind I am using: 在后面的代码中,我正在使用:

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

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

This just throws an error of "cant convert void to System.Collections.IEnumerable" I also think this isn't correct. 这只是抛出“无法将void转换为System.Collections.IEnumerable”的错误,我也认为这是不正确的。

Im trying to bind it to an observable collection in the view model. 我试图将其绑定到视图模型中的可观察集合。

The view model: 视图模型:

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

        }
    }

When setting the binding in the Xaml this binding works fine. 在Xaml中设置绑定时,此绑定可以正常工作。 The issue is not observable collection the issue is that I have no idea how to set the binding in the code behind. 问题不是可观察的集合,问题是我不知道如何在后面的代码中设置绑定。

Summary: 摘要:

I need to know how to do this (itemsource binding): 我需要知道如何执行此操作(itemsource绑定):

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


</ListView>

In the code behind. 在代码后面。

Any help would be appreciated. 任何帮助,将不胜感激。

To programmatically set binding on a control, you have to pass it as parameter in extension method. 要以编程方式设置控件上的绑定,必须将其作为参数传递给扩展方法。 Reference links: extension methods , or member method 参考链接: 扩展方法成员方法

For example, try: 例如,尝试:

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

This sets a binding between path as 'routeLabels' and control's BindingContext which is the view model. 这将路径设置为“ routeLabels”和控件的BindingContext (即视图模型)之间的绑定。

Also, would recommend changing 'routeLabels' to 'RouteLabels' as per standard naming policy for C# properties. 另外,建议根据C#属性的标准命名策略将“ routeLabels”更改为“ RouteLabels”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM