我正在使用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的索引
最佳答案
该对象很可能不是发送方,而是控件传递的CommandParameter
。您可以将按钮的CommandParameter
绑定(bind)到自身以模仿sender
。
CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
(但这可能并不能真正帮到您那么多,所以请思考一下您通过的内容可以帮助您获得该值(value)。)