"Bin" command in MenuItem

1

Good morning,

I added the Command property to a MenuItem but it does not work

The code of the xaml is the following:

<ListView
    ItemsSource="{Binding Categorias}"
    SelectedItem="{Binding SelectedCategoria, Mode=TwoWay}"
    HasUnevenRows="false"
    RowHeight="55"
    Margin="40,0,25,0">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <ViewCell.ContextActions>
            <MenuItem Text="Ver" />
            <MenuItem Text="Eliminar"
                      Command="{Binding EliminarCategoria}" />
            </ViewCell.ContextActions>
          <templates:CategoriaListItemTemplate/>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>

The code of the ViewModel is as follows:

public CategoriasViewModel(
ICategoriasService categoriaService,
ISqliteService sqliteService,IUserDialogs  userDialogService)
    {
        _categoriaService = categoriaService;
        _sqliteService = sqliteService;
        _userDialogService = userDialogService;

        EliminarCategoria = new Command(ExecuteEliminarCategoria);


    }

    public Command EliminarCategoria { get; private set; }
    private async void ExecuteEliminarCategoria()
    {
        var categoria = SelectedCategoria;

        var sqlCategoria = new Models.Categorias.SqlCategorias
        {
            idCategoria = categoria.idCategoria,
            name = categoria.name,
            activated = false
        };

        await _sqliteService.Insert(sqlCategoria);


        _userDialogService.Toast("Categoria eliminada del catálogo.");

    }

What can I be doing wrong?

Thank you.

    
asked by Fel 31.01.2017 в 13:18
source

1 answer

0
  

The problem is that the bin context (BindingContex) inside your ItemTemplate is obviously only your Item, so access the command defined in the ViewModel and not the object itself is a bit more difficult.

But we can solve it like this:

The code of the xaml is the following:

<ContentPage ...
    x:Name="CurrentPage">

<ListView
    ItemsSource="{Binding Categorias}"
    SelectedItem="{Binding SelectedCategoria, Mode=TwoWay}"
    HasUnevenRows="false"
    RowHeight="55"
    Margin="40,0,25,0">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <ViewCell.ContextActions>
            <MenuItem Text="Ver" />
            <MenuItem Text="Eliminar" Command="{Binding BindingContext.EliminarCategoria,Source={x:Reference CurrentPage}}" />
            </ViewCell.ContextActions>
          <templates:CategoriaListItemTemplate/>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
...
</ContentPage>

Why use Source?

When using Source only in the command, the rest of the template still has as context the Item, which is appropriate for a Template.

Good luck, I hope it serves you.

    
answered by 17.05.2017 в 23:06