在我的视图模型中,下面的XAML正在绑定到delete命令:
<TextCell.ContextActions>
<MenuItem Command="{Binding Path=BindingContext.DeleteCollectionCommand, Source={x:Reference Name=CollectionListView}}"
CommandParameter="{Binding .}"
Text="Delete"
IsDestructive="True" />
</TextCell.ContextActions>
我正在尝试将它转换为C#,这样我就可以编程地使用它了。
我试过以下几种方法,但不起作用。有什么需要改变的?是否有更好/不同的方式访问ViewModel DeleteCommand?
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background
deleteAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
deleteAction.SetBinding(MenuItem.CommandProperty,
new Binding("BindingContext.DeleteCommand", BindingMode.Default, null, null, null, "{x:Reference Name=CollectionBeerListView}"));
ContextActions.Add(deleteAction);
}
编辑
通过结合skar的答案和从父视图初始化单元格,我就能够做到这一点:
lstView.ItemTemplate = new DataTemplate(() =>
{
var cell = new DeleteGenericListItemTemplate(page);
return cell;
});
不确定这是否理想..。但却让我继续前进。
发布于 2016-08-16 06:22:31
如果您在文本单元格上扩展以创建如下内容,并引用您的页面,您应该能够通过页面的绑定上下文访问您的DeleteCommand:
public class CustomCell: TextCell
{
public CustomCell(Page page)
{
var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background
deleteAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
deleteButton.SetBinding (MenuItem.CommandProperty, new Binding ("BindingContext.DeleteCommand", source: page));
ContextActions.Add(deleteAction);
}
}
发布于 2021-02-02 15:41:26
我通过向我的(自定义)视图单元格添加一个ParentContext属性来修正这个问题。通过使用ViewModel将该属性设置为AncestorType,如下所示:
ParentContext="{Binding ., Source={RelativeSource AncestorType={x:Type local:MyViewModel}}}"
我的自定义视图单元格:
public static readonly BindableProperty ParentContextProperty = BindableProperty.Create("ParentContext", typeof(object), typeof(CustomViewCell), null, BindingMode.OneTime);
public object ParentContext
{
get { return GetValue(ParentContextProperty); }
set { SetValue(ParentContextProperty, value); }
}
然后,在我的viewcell中,我引用viewcell x:Name添加了contextaction,它可以工作:)
<ViewCell.ContextActions>
<MenuItem
Command="{Binding ParentContext.TheCommand, Source={x:Reference customViewCellName}}"
CommandParameter="{Binding Id}"
Text="Some text">
</MenuItem>
</ViewCell.ContextActions>
https://stackoverflow.com/questions/38943452
复制相似问题