Xamarin Forms元素的Parent属性为空

5

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

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

在ViewCell内,我希望有一个函数来访问ListView的itemSource以删除一个项目。我认为可以通过在ViewCell内访问Parent属性来实现这一点。

ListView parent = (ListView)this.Parent;

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


你尝试过使用 view.ParentForAccessibility 吗? - Majkl
1
一般来说,你不应该从 UI 直接编辑 ListView.ItemsSource。最好在你的 ViewModel 中拥有一个 ObservableCollection<> 来存储项目,并配合一个操作它的 Command 使用。 - foxanna
所以我的ViewModel里面有一个ObservableCollection<>。我怎样才能从ViewCell内部访问viewmodel?我想使用一个带有命令的MenuItem,但我不知道如何从该命令访问ViewModel。 - nassan
我删除了我的回答,因为它在Xamarin.Forms中不起作用(在Xamarin.Android中可以),抱歉。 - Majkl
2个回答

4

有一个覆盖方法,你必须调用它,那么父对象将不会为空

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

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

            }
        }

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);

但是每个“ViewCell”的“bindingcontext”都是视图模型中的“observeablecollection<>”中的一个对象。我该如何将“ViewCell”绑定到实际的视图模型? - nassan
啊,说得好。你可以在集合中的每个项目上定义命令,并让它调用父VM中的方法;但尝试使用消息传递方法可能更容易。 - Jason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接