[英]Xamarin Forms Element Parent property is null
I have a ViewCell
that is used as an item template for a ListView
: 我有一个
ViewCell
用作ListView
的项目模板:
ListView details_list = new ListView ();
details_list.ItemTemplate = new DataTemplate(typeof(CartViewCell));
Inside the ViewCell I would like to have a function to access the ListView's itemSource in order to delete an item. 在ViewCell中我想要一个函数来访问ListView的itemSource以删除一个项目。 I though I would do this by accessing the
Parent
property inside the ViewCell
我虽然通过访问
ViewCell
的Parent
属性来做到这ViewCell
ListView parent = (ListView)this.Parent;
But when I attempt this, it shows the parent to be null. 但是当我尝试这个时,它会显示父项为null。 Is this an incorrect way to be using the
Parent
property? 这是使用
Parent
属性的错误方法吗? What am I missing? 我错过了什么?
there is an override method you have to call it then the parent will not be null 有一个覆盖方法,你必须调用它,然后父级将不为空
protected override void OnParentSet()
{
object view = Parent;
base.OnParentSet();
if (view.GetType() == typeof(Grid))
{
}
}
There are a couple of ways to solve this; 有几种方法可以解决这个问题; two possibilities include
两种可能性包括
Define a Command in your ViewModel, 在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
}
and then in your ViewCell bind to it 然后在你的ViewCell绑定它
<Button Command="{Binding DeleteCommand}" CommandParameter="{Binding ID}" Text="Delete" />
In your ViewModel, subscribe to a message: 在ViewModel中,订阅消息:
MessagingCenter.Subscribe<MyViewCell, string> (this, "Delete", (sender, id) => {
// do the appropriate delete action here
});
In your ViewCell, send the message whenever they click the button (or whatever triggers the action) - ID should be and identifier for the particular item 在您的ViewCell中,只要他们点击按钮(或触发操作的任何内容)就发送消息 - ID应该是特定项目的标识符
MessagingCenter.Send<MyViewCell, string> (this, "Delete", ID);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.