Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clickable ItemsControl item in WPF

Tags:

onclick

wpf

grid

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.

like image 668
Adam Haile Avatar asked Aug 28 '11 01:08

Adam Haile


2 Answers

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>
like image 102
H.B. Avatar answered Sep 24 '22 09:09

H.B.


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)
    {
    }        
like image 34
fatty Avatar answered Sep 22 '22 09:09

fatty