问题
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
回答1:
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.)
来源:https://stackoverflow.com/questions/7942093/object-sender-is-always-null-in-relaycommand