Clickable ItemsControl item in WPF

2019-06-17 18:48发布

问题:

I'm using an ItemsControl to display a list of databound items, for each the core of the DataTemplate is a Grid upon which I've placed all the bound controls.

I would like to be able to click on the entire area for each item in the list. But I cannot figure out how to make the area clickable.

Any suggestions of how to make an entire grid area clickable would be great.

回答1:

You can use the AttachedCommandBehavior classes from C# Disciples to achieve this.

Define a command in the ViewModel, and then on the Grid object use the ACB AttachedProperties to bind the MouseLeftButtonUp event to the command.

Some code to get you started:

        <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>

Edit for non-MVVM solution.

The above code snippet will still work when you have not designed your application following the MVVM guide-lines as you are essentially just binding to a command in the code-behind.

However, if you don't want to go to the trouble of defining commands, you can simply specify an event to hook to, like so:

<Grid MouseLeftButtonUp="Grid_MouseLeftButtonUp"> in the XAML file.

and in the code-behind:

    private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
    }        


回答2:

To make something clickable you can usually wrap it in a Button, if it should be "invisible" you can change the template:

<Button.Template>
    <ControlTemplate TargetType="{x:Type Button}">
        <ContentPresenter />
    </ControlTemplate>
</Button.Template>


标签: wpf grid onclick