Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms XAML ContextAction Binding to C# in ViewCell

I have the following XAML working to bind to a delete command in my view model:

        <TextCell.ContextActions>
          <MenuItem Command="{Binding Path=BindingContext.DeleteCollectionCommand, Source={x:Reference Name=CollectionListView}}"
                    CommandParameter="{Binding .}"
                    Text="Delete" 
                    IsDestructive="True" />
        </TextCell.ContextActions>

I'm trying to convert it to C# so I can programmatically use it.

I've tried the following but it's not working. What needs to be changed? Is there a better/different way to access the 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);
    }

EDIT

I was able to get this working by combining skar's answer and initializing the Cell like this from the parent view:

        lstView.ItemTemplate = new DataTemplate(() =>
        {
            var cell = new DeleteGenericListItemTemplate(page);
            return cell;
        });

Not sure if this is ideal.. but keeps me moving.

like image 565
aherrick Avatar asked Dec 10 '25 13:12

aherrick


1 Answers

if you extend on the text cell to create something like below with a reference to your page you should be able to access your DeleteCommand on your ViewModel through the binding context of the page:

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


        }
}
like image 181
skar Avatar answered Dec 14 '25 05:12

skar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!