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

时间:2011-10-29 22:28:59

标签: wpf mvvm icommand relaycommand

我正在使用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;
    }

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>

我需要在ExpandClickCommand

中获取当前ListboxItem的索引

1 个答案:

答案 0 :(得分:10)

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

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

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