ItemsControl 中 CheckBox 上 MiddleClick 的 WPF 命令参数

问题描述

当我在 ItemsControl 中的复选框上使用 MiddleClick 时,我想触发一个命令。我需要将项目源作为命令参数返回。我在 XAML 中尝试了两种方法

方法一:

<ItemsControl x:Name="CheckBoxItems" ItemsSource="{Binding Curves}" Grid.Row="1">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" Margin="0,5,0"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.InputBindings>
        <MouseBinding Gesture="MiddleClick" Command="{Binding SelectOnlyCommand}"
                      CommandParameter="{Binding }"/>
    </ItemsControl.InputBindings>
</ItemsControl>

方法将 UserControl 返回给命令而不是项目源。

方法二:

<ItemsControl x:Name="CheckBoxItems" ItemsSource="{Binding Curves}" Grid.Row="1">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" Margin="0,0">
                <CheckBox.InputBindings>
                    <MouseBinding Gesture="MiddleClick" Command="{Binding Path=SelectOnlyCommand}"
                                  CommandParameter="{Binding }"/>
                </CheckBox.InputBindings>
            </CheckBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    
</ItemsControl>

方法不会触发 SelectOnlyCommand。感谢您的帮助。

解决方法

(已编辑) 如果你想传递单个项目,它的工作方式如下:

 <ItemsControl x:Name="CheckBoxItems" ItemsSource="{Binding Curves}" Grid.Row="1">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" Margin="0,5,0">
                        <CheckBox.InputBindings>
                            <MouseBinding Gesture="MiddleClick" Command="{Binding ElementName=CheckBoxItems,Path=DataContext.SelectOnlyCommand}"
                                          CommandParameter="{Binding }"/>
                        </CheckBox.InputBindings>
                    </CheckBox>
                </DataTemplate>
            </ItemsControl.ItemTemplate>                
        </ItemsControl>
,

您可以通过方式 2 实现这一点,但问题是您无法绑定 Command。您必须通过 ElementName 绑定它。

  <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" Margin="0,Path = DataContext.SelectOnlyCommand}"
                                          CommandParameter="{Binding }"/>
                        </CheckBox.InputBindings>
                    </CheckBox>