对象发送方在RelayCommand中始终为null

Eam*_*voy 2 wpf mvvm relaycommand icommand

我正在使用RelayCommand处理按钮单击,我需要获取sender参数,但它始终为null,任何想法为什么?

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;
    }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我需要在ExpandClickCommand中获取当前ListboxItem的索引

H.B*_*.B. 10

该对象很可能不是发送者,而是CommandParameter由控件传递的.您可以将CommandParameter按钮绑定到自身以模仿sender.

CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
Run Code Online (Sandbox Code Playgroud)

(但这可能对你没有多大帮助,所以想想你传递的内容可以帮助你获得这个价值.)