Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

object sender is always null in RelayCommand

I am using RelayCommand to handle a button click, I need to get the sender parameter but it is always null, any idea why?

ViewModel.cs

    private RelayCommand _expandClickCommand;
    public ICommand ExpandClickCommand
    {
        get
        {
            if (_expandClickCommand == null)
            {
                _expandClickCommand = new RelayCommand(ExpandClickCommandExecute, ExpandClickCommandCanExecute);
            }
            return _expandClickCommand;
        }
    }

    public void ExpandClickCommandExecute(object sender)
    {
        //sender is always null when i get here! 
    }
    public bool ExpandClickCommandCanExecute(object sender)
    {
        return true;
    }

View.xaml

<ListBox ItemsSource="{Binding Path=MyList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <Button Grid.Column="0" Grid.Row="0" Content="Expand" Command="{Binding DataContext.ExpandClickCommand,ElementName=SprintBacklog}"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I need to get the index of the currect ListboxItem in ExpandClickCommand

Upvotes: 3

Views: 7162

Answers (1)

brunnerh
brunnerh

Reputation: 184376

That object in all likelihood is not the sender but the CommandParameter that is passed by the control. You could bind the CommandParameter of the button to itself to immitate the sender.

CommandParameter="{Binding RelativeSource={RelativeSource Self}}"

(But that might not really help you that much, so think about what you pass in that helps you get that value.)

Upvotes: 13

Related Questions