Clickable ItemsControl item in WPF

天涯浪子 提交于 2019-12-23 08:13:09

问题


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>


来源:https://stackoverflow.com/questions/7218424/clickable-itemscontrol-item-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!