Search code examples
wpfxamldatatemplatecontroltemplate

Handling Button's Click Command Inside ListView


Let's say I have a simple ListView with a single button in it's Gridview's only column:

<ListView x:Name="SomeListView" ItemsSource="{Binding Whatever}">
    <ListView.View>
        <GridView>
             <GridViewColumn CellTemplate="{StaticResource myCellTemplate}" Header="ColumnHeader"/>
        </GridView>
    </ListView.View>
</ListView>

And myCellTemplate looks like this:

<DataTemplate x:Key="myCellTemplate">
    <Viewbox>
        <Button x:Name="mybutton" Command="{Binding myClickCommand}" Content="{Binding btnBinding}"></Button>
    </Viewbox>
</DataTemplate>

With myClickCommand an ICommand in my VM. At this point, everything is hunky-dory and a user's click of my button calls myClickCommand as you would expect. Now, I want to add some mouseover styling to to my rows, so I add an ItemContainerStyle like this:

<ListView x:Name="SomeListView" ItemContainerStyle="{StaticResource myItemStyle}" ItemsSource="{Binding Whatever}">
    ...
</ListView>

With myItemStyle as:

<Style x:Key="myItemStyle" TargetType="{x:Type ListViewItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Grid>
                    <Border x:Name="borderMain" BorderThickness="1" BorderBrush="Transparent">
                        <GridViewRowPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                    <Rectangle x:Name="rectGlass" Fill="LightGray" Opacity=".2" Visibility="Hidden"></Rectangle>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter TargetName="borderMain" Property="BorderBrush" Value="DarkGray" />
                        <Setter TargetName="rectGlass" Property="Visibility" Value="Visible"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

At this point, the user's click doesn't trigger myClickCommand, presumably because the event is not routing to the button. Is there some way to achieve this?


Solution

  • Your Rectangle (rectGlass) is on top of the Button. The button is not receiving the click event because it is never actually getting clicked.