0

这是我的控制:

<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

4

1 回答 1

1

尝试添加CommandParameter={Binding}到您的<Button>. 这将通过该ICommand.Execute方法将所选项目的数据上下文传递到您的命令中。

否则,将命令属性移动到表示项目的模型,而不是在根级别定义一组命令。我个人更喜欢这种方法。我喜欢我的命令是无参数的,并且总是作用于包含命令的视图模型类。

于 2013-06-13T17:06:39.087 回答