[英]Xamarin Forms Element Parent property is null
我有一个ViewCell
用作ListView
的项目模板:
ListView details_list = new ListView ();
details_list.ItemTemplate = new DataTemplate(typeof(CartViewCell));
在ViewCell中我想要一个函数来访问ListView的itemSource以删除一个项目。 我虽然通过访问ViewCell
的Parent
属性来做到这ViewCell
ListView parent = (ListView)this.Parent;
但是当我尝试这个时,它会显示父项为null。 这是使用Parent
属性的错误方法吗? 我错过了什么?
有一个覆盖方法,你必须调用它,然后父级将不为空
protected override void OnParentSet()
{
object view = Parent;
base.OnParentSet();
if (view.GetType() == typeof(Grid))
{
}
}
有几种方法可以解决这个问题; 两种可能性包括
在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" />
在ViewModel中,订阅消息:
MessagingCenter.Subscribe<MyViewCell, string> (this, "Delete", (sender, id) => {
// do the appropriate delete action here
});
在您的ViewCell中,只要他们点击按钮(或触发操作的任何内容)就发送消息 - ID应该是特定项目的标识符
MessagingCenter.Send<MyViewCell, string> (this, "Delete", ID);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.