Here's my control:
<UserControl.Resources>
<DataTemplate x:Key="ItemTemplate">
<Border BorderThickness="0.5" BorderBrush="DarkGray">
<Grid Height="30">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox Command="{Binding DataContext.CheckCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" Content="{Binding Name}" IsChecked="{Binding IsChecked}" Grid.RowSpan="2" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" Width="Auto"/>
<Button Command="{Binding DataContext.UpCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
Grid.Row="0" Grid.Column="1" HorizontalAlignment="Right" Margin="1" ToolTip="Up" BorderBrush="{x:Null}" Background="{x:Null}">
<Image Source="/Resources/Icons/sort_up.png"/>
</Button>
<Button
Command="{Binding DataContext.DownCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right" Margin="1" ToolTip="Down" BorderBrush="{x:Null}" Background="{x:Null}">
<Image Source="/Resources/Icons/sort_down.png"/>
</Button>
</Grid>
</Border>
</DataTemplate>
</UserControl.Resources>
And the code in the View Model includes this:
/// <summary>
/// Moves item up in the custom list
/// </summary>
private void UpCommandExecuted()
{
if (SelectedItem != null)
{
StoredProc Proc = SelectedItem;
int oldLocation = TheList.IndexOf(SelectedItem);
if (oldLocation > 0)
{
if (SelectedItem.IsChecked || (TheList[oldLocation - 1].IsChecked == SelectedItem.IsChecked))
{
TheList.RemoveAt(oldLocation);
TheList.Insert(oldLocation - 1, Proc);
SelectedItem = Proc;
}
}
}
}
I also have a SelectedItem
property in VM that is a StoredProcedure
(type I made up). This is working, but clicking any of the listbox's item "Up" button causes the SELECTEDITEM to be acted on. I actually want the listbox item where I click the button to be acted on. How can I do this? How do I tell my UpCommandExecuted()
method to act on the ListBoxItem where I clicked the Up button, not the actual SelectedItem
?