Passing and Catching the CommandParameter of a Xamarin Forms Button

2

How to pass a value that is in a Binding by the CommandParameter of a button that is within a ListView to ViewModel ?

The button is accessing Command right, but I do not know if this is how CommandParameter passes or how to get its value in ViewModel .

How can I do this?

My code:

\\ XAML

<ListView x:Name="lvEnderecos" RowHeight="205">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
            <Label x:Name="lblCEP" Font="14" TextColor="Black" Text="{Binding CliEndCep, StringFormat='CEP: {0}'}"></Label>
              <Grid x:Name="GridControl3" RowSpacing="0" ColumnSpacing="0">
                <Grid.RowDefinitions>
                  <RowDefinition Height="25"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="Auto" />
                  <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <StackLayout x:Name="stkManipularEndereco" Grid.Row="0" Grid.Column="0" Padding="5, 0, 0, 0" HeightRequest="25" WidthRequest="25">
                  <Button x:Name="btnEditarEndereco" BackgroundColor="Transparent" Image="editar2.png" HeightRequest="25" WidthRequest="25" BindingContext="{Binding Source={x:Reference lvEnderecos}, Path=BindingContext}" Command="{Binding EditarEnderecoCommand}" CommandParameter="{Binding CliEndCep}" />
                </StackLayout>
              </Grid>
            </StackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>

\\ ViewModel

    this.EditarEnderecoCommand = new Command(async () =>
    {
        try
        {
             page.DisplayAlert("Alerta", "Você clicou aqui :)", "OK");
        }                
        catch (Exception ex)
        {
             throw ex;
        }
    }
});
    
asked by anonymous 27.12.2016 / 19:15

1 answer

2

I found the solution to my problem, I added the name to ContentPage which in the case contains my ListView and the other components.

So:

x:Name="MeusEnderecosView"

In my Command I added BindingContext referencing the name of this ContentPage .

This way:

Command="{Binding Path=BindingContext.ExcluirEnderecoCommand, Source={x:Reference MeusEnderecosView}}"

And CommandParameter looks like this:

CommandParameter="{Binding .}"

And in ViewModel , to get the value of some Binding of View is just to do this:

this.ExcluirEnderecoCommand = new Command<Endereco>(async (model) => 
{
     Endereco objEnd = new Endereco();
     objEnd.EndCep = model.EndCep;
     objEnd.EndCodigo = model.EndCodigo;
});
    
29.12.2016 / 11:58