3

我正在使用 RelayCommand 来处理按钮单击,我需要获取 sender 参数但它始终为空,知道为什么吗?

视图模型.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;
    }

查看.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 的索引

4

1 回答 1

13

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

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

(但这可能对您没有太大帮助,因此请考虑一下您传递的内容可以帮助您获得该价值。)

于 2011-10-29T22:34:29.973 回答