WPF中的Clickable ItemsControl项

Ada*_*ile 7 wpf grid onclick

我正在使用ItemsControl来显示数据绑定项的列表,因为DataTemplate的每个核心都是一个Grid,我已经放置了所有绑定控件.

我希望能够点击列表中每个项目的整个区域.但我无法弄清楚如何使该区域可点击.

任何关于如何使整个网格区域可点击的建议都会很棒.

H.B*_*.B. 14

要使可点击的东西你通常可以将它包装在一个Button中,如果它应该是"隐形的"你可以更改模板:

<Button.Template>
    <ControlTemplate TargetType="{x:Type Button}">
        <ContentPresenter />
    </ControlTemplate>
</Button.Template>
Run Code Online (Sandbox Code Playgroud)

  • +1:在我的一生中,我无法相信在我用 XAML 编写的四年里我从未想过这样做。 (2认同)

fat*_*tty 4

您可以使用C# Disciples 中的 AttachedCommandBehavior 类来实现此目的。

在 ViewModel 中定义一个命令,然后在 Grid 对象上使用 ACB AttachedProperties 将MouseLeftButtonUp事件绑定到该命令。

一些帮助您入门的代码:

        <Grid Name="grid" Height="30" ForceCursor="True" Cursor="Hand">
            <acb:CommandBehaviorCollection.Behaviors>
                <acb:BehaviorBinding Event="MouseLeftButtonUp" Command="{Binding Path=DataContext.EditEventCommand, RelativeSource={RelativeSource AncestorType={x:Type self:Dashboard}}}" CommandParameter="{Binding}" />
            </acb:CommandBehaviorCollection.Behaviors>
        </Grid>
Run Code Online (Sandbox Code Playgroud)

编辑非 MVVM 解决方案。

当您没有按照 MVVM 指南设计应用程序时,上面的代码片段仍然有效,因为您本质上只是绑定到代码隐藏中的命令。

但是,如果您不想麻烦地定义命令,则可以简单地指定要挂钩的事件,如下所示:

<Grid MouseLeftButtonUp="Grid_MouseLeftButtonUp">在 XAML 文件中。

并在隐藏代码中:

    private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
    }        
Run Code Online (Sandbox Code Playgroud)