Xamarin获取ListItem上下文

时间:2017-05-29 13:30:15

标签: xamarin binding xamarin.forms

我有一个用户控件,我包含在ListView中,我想在用户控件基于listitem绑定初始化时添加动态内容。我不知道该怎么做。请参阅"我如何绑定这个???" ...我认为我应该以某种方式将我的PropertyBinding绑定到listitem?

这是我使用listview的原始视图

using System;
using System.Collections.Generic;
using EngineerApp.ViewModels;
using Xamarin.Forms;

namespace EngineerApp
{
    public partial class AuthorisationBar : ContentView
    {
        public static readonly BindableProperty GigProperty = BindableProperty.Create("SelectedGig", typeof(GigViewModel), typeof(AuthorisationBar), new GigViewModel());

        public GigViewModel SelectedGig
        {
            get
            {
                return (GigViewModel)GetValue(GigProperty);
            }

            set
            {
                SetValue(GigProperty, value);
            }
        }

        public AuthorisationBar()
        {
            InitializeComponent();

            BindingContext = this;

        }
    }
}

然后是用户控制xaml。

Model.all.each do |model|
  model.image.recreate_versions!(:version1, :version2)
end

这里是用户控件背后的代码

{{1}}

更新1 - 更新了所有页面以反映最新建议。使用{Binding。}我现在得到以下错误:

"无法分配属性" SelectedGig":属性不存在,或者不可分配,或者值和属性之间的类型不匹配"

2 个答案:

答案 0 :(得分:0)

我为我当前的项目做了类似的事情 - 将当前项目的ID传递给我的ViewModel(来自您发布的代码,似乎您没有使用正确的分离MVVM范例下的关注点 - 虚拟机不应该在您的视图中初始化任何内容):

<Button Text="Reconnect" Command="{Binding Path=BindingContext.ReconnectCommand, Source={x:Reference Name=ServicesList}}" CommandParameter="{Binding}" VerticalOptions="Center"/>

作为参考,传递命令的按钮嵌入在ListView.DataTemplate中,并传递列表项的ID,它是

的一部分。

答案 1 :(得分:0)

试试这个:

<local:AuthorisationBar SelectedGig="{Binding .}"></local:AuthorisationBar>

其中“。”将是列表中的“当前”项目。

注意我在代码中使用了SelectedGid,因为这是您定义自定义控件的属性的名称,而不是SelectedGigId

此外,您需要从自定义控件的构造函数中删除此行:

BindingContext = SelectedGig;

BindingContext已经是GigViewModel

类型

希望这有帮助!

<强>更新

您的自定义控制代码应该是:

public partial class AuthorisationBar : ContentView
{
    public AuthorisationBar()
    {
        InitializeComponent();
    }

    public static readonly BindableProperty SelectedGigProperty = BindableProperty.Create(nameof(SelectedGig), typeof(GigViewModel), typeof(AuthorisationBar), null);

    public GigViewModel SelectedGig
    {
        get
        {
            return (GigViewModel)GetValue(SelectedGigProperty);
        }
        set
        {
            SetValue(SelectedGigProperty, value);
        }
    }
}

如前所述,您无需为BindingContext

设置任何内容

更新2

回答你的问题。错误是您的自定义控件的BindableProperty不符合命名约定要求。

来自Xamarin BindableProperty documentation

  

可绑定属性的命名约定是可绑定属性标识符必须与Create方法中指定的属性名称匹配,并在其后附加“Property”。

这就是为什么将BindableProperty从GigProperty更新为SelectedGigProperty修复了您的问题。