Listview DataTemplateSelector将参数传递给DataTemplate

时间:2016-11-17 08:51:01

标签: listview xamarin.forms

我需要将ObservableCollection作为参数发送到我的自定义视单元,该视图通过DataTemplateSelector调用。有什么想法吗?

我想要的是在用户点击每个项目中包含的按钮时删除一个Listviewitem。

以下是TemplateSelector中的代码:

private readonly DataTemplate templateOne;
private readonly DataTemplate templateTwo;

public ItemTemplateSelect(ObservableCollection<Item> _items)
{
    templateOne = new DataTemplate(typeof(TemplateOneCell));
    templateTwo = new DataTemplate(typeof(TemplateTwoCell));
}

protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
    if (((Item)item).status == -1)
    {
        return templateOne; <---- Here I want to send '_items' as parameter
    }
    else
    {
        return templateTwo;
    }
}

以下是我的viewcell示例:

public class ContactCell : ViewCell
{
    public ContactCell()
    {
        var okButton = new Button()
        {
            Text = "OK"
        };
        okButton.Clicked += okButton_Clicked;

        var frame = new Frame
        {
            Padding = 0,
            Margin = 0,
            Content = okButton
        };

        View = frame;
    }

    private async void okButton_Clicked(object sender, EventArgs e)
    {
        -------------> delete current item
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

问题是,如果你使用静态值,你知道我们不能使用Navigation.pushasync函数。所以我会给你和示例如何没有静态值。但我不知道这是否是最短的做事方式。我所做的是创建所选对象的实例和一个将在listview datatemplate中打开新表单并使用bindableproperty将datatemplate传递给viewcell的函数。在你的viewcell中,在你的按钮的clickevent中调用(datatemplate)函数。

想象一下你的项目

class myobject
{
...
}

并创建列表视图

public class mylistviewTemplate:ListView
{
 public mylistviewTemplate()
 {
   ...
   DataTemplate cell = new DataTemplate (typeof(myobjectcellview));
   cell.SetValue(myobjectcellview.myClickedObject,this);
 }
 public void tapped(myobject item)
{

    Navigation.PushAsync (new myobjectDetailPage (item));
}
...

在你的手机视图中

public class myobjectcellview:ViewCell
{
public static readonly BindableProperty myClickedObject = 
BindableProperty.Create<myobjectcellview, mylistviewTemplate>(bip => bip.obj, null);

    public mylistviewTemplate obj
    {
        get {return (mylistviewTemplate)GetValue(myClickedObject);}
        set {SetValue(myClickedObject, value);}
    }
    public myobjectcellview()
    {
      Button btn = new Button();
      btn.Clicked += (sender, e) =>
         {
            if (obj != null)
            {
                var ctx = (myobject)this.BindingContext;
                obj.tapped(ctx as myobject);    
            }
        };
      this.View = new StackLayout{...};
    }