4

我有一个ViewCell用作 a 的项目模板ListView

ListView details_list = new ListView ();
details_list.ItemTemplate = new DataTemplate(typeof(CartViewCell));

在 ViewCell 内部,我想要一个函数来访问 ListView 的 itemSource 以删除一个项目。我虽然我会通过访问Parent里面​​的属性来做到这一点ViewCell

ListView parent = (ListView)this.Parent;

但是当我尝试这样做时,它显示父级为空。这是使用Parent房产的不正确方式吗?我错过了什么?

4

2 回答 2

3

有一个覆盖方法你必须调用它然后父级不会为空

protected override void OnParentSet()
        {
            object view = Parent;
            base.OnParentSet();

            if (view.GetType() == typeof(Grid))
            {

            }
        }
于 2017-10-15T12:11:08.990 回答
0

有几种方法可以解决这个问题;两种可能性包括

  1. 使用命令

在您的 ViewModel 中定义一个命令,

// define a command property
public ICommand DeleteCommand { get; set; }

// in your constructor, initialize the command
DeleteCommand = new Command<string>((id) =>
{
  // do the appropriate delete action here
}

然后在您的 ViewCell 中绑定到它

<Button Command="{Binding DeleteCommand}" CommandParameter="{Binding ID}" Text="Delete" />
  1. 使用消息传递

在您的 ViewModel 中,订阅一条消息:

MessagingCenter.Subscribe<MyViewCell, string> (this, "Delete", (sender, id) => {
    // do the appropriate delete action here
});

在您的 ViewCell 中,每当他们单击按钮(或任何触发操作)时发送消息 - ID 应该是特定项目的标识符

MessagingCenter.Send<MyViewCell, string> (this, "Delete", ID);
于 2015-10-27T14:36:10.453 回答