I'm trying to fire a Command
in my ViewModel
when the selected item changes, passing the whole object as parameter. The SelectedCondicaoPagamento
is the default value. How can I do that?
the Model
public class CaptacaoPedidoItem : Notifier
{
//displays all 'CondicaoPagamento'
public List<CondicaoPagamento> CondicoesPagamento { get; set; }
private CondicaoPagamento _selectedCondicaoPagamento;
public CondicaoPagamento SelectedCondicaoPagamento
{
get
{
return _selectedCondicaoPagamento;
}
set
{
_selectedCondicaoPagamento= value;
NotifyPropertyChanged();
}
}
}
the ViewModel
public class CaptacaoViewModel : Notifier
{
public Command PlanoPagamentoAlteradoCommand => new Command(PlanoPagamentoAlterado);
public List<CaptacaoPedidoItem> ItensPedido
{
get
{
return _itensPedido;
}
set
{
_itensPedido = value;
NotifyPropertyChanged();
}
}
//it's not called
public void PlanoPagamentoAlterado()
{
}
}
the View
<ListView Grid.Row="3" x:Name="listasugestao" ItemsSource="{Binding ItensPedido}" RowHeight="80">
{...}
<Picker
ItemsSource="{Binding CondicoesPagamento}"
SelectedItem="{Binding SelectedCondicaoPagamento}"
ItemDisplayBinding="{Binding NomePlanoPagamento}"
Grid.Column="6" VerticalOptions="Center" HorizontalOptions="FillAndExpand">
<Picker.Behaviors>
<behaviors:EventHandlerBehavior EventName="SelectedIndexChanged">
<behaviors:InvokeCommandAction Command="{Binding PlanoPagamentoAlteradoCommand}" />
</behaviors:EventHandlerBehavior>
</Picker.Behaviors>
</Picker>
</ListView>
This solution uses the reusable EventToCommandBehavior published by Microsoft. I took the liberty of also sending the viewmodel object bound to the respective cellview as a command parameter. That way it is easy to find out in what cell of your list actually changed.
<Picker
ItemsSource="{Binding CondicoesPagamento}"
SelectedItem="{Binding SelectedCondicaoPagamento}"
ItemDisplayBinding="{Binding NomePlanoPagamento}"
Grid.Column="6" VerticalOptions="Center" HorizontalOptions="FillAndExpand">
<Picker.Behaviors>
<behaviors:EventToCommandBehavior
EventName="SelectedIndexChanged"
Command="{Binding Path=BindingContext.PlanoPagamentoAlteradoCommand, Source={x:Reference Name=listasugestao}}"
CommandParameter="{Binding}"/>
</Picker.Behaviors>
</Picker>
public class CaptacaoViewModel : Notifier
{
public CaptacaoViewModel()
{
PlanoPagamentoAlteradoCommand = new Command<CaptacaoPedidoItem>(WhenSelectedIndexChanged);
}
public Command PlanoPagamentoAlteradoCommand {get;}
public List<CaptacaoPedidoItem> ItensPedido
{
get
{
return _itensPedido;
}
set
{
_itensPedido = value;
NotifyPropertyChanged();
}
}
private void WhenSelectedIndexChanged(CaptacaoPedidoItem item)
{
// do something
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With