这是我的控制:
<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>
View Model 中的代码包括:
/// <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;
}
}
}
}
我SelectedItem
在 VM 中也有一个属性StoredProcedure
(我编的类型)。这是可行的,但是单击列表框的任何项目“向上”按钮会导致 SELECTEDITEM 被执行。我实际上想要单击要操作的按钮的列表框项目。我怎样才能做到这一点?如何告诉我的UpCommandExecuted()
方法对我单击 Up 按钮的 ListBoxItem 进行操作,而不是实际的SelectedItem
?