简体   繁体   中英

Can't access the events inside the GridViewColumn's Content

When I add an event to the ListViewItem ,

<Style TargetType="{x:Type ListViewItem}">
    <EventSetter Event="PreviewMouseDown" Handler="listViewItem_MouseDown" />
</Style>

Then add another event in the content inside the GridViewColumn ,

<GridViewColumn Header="Action">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <Image x:Name="imgEdit"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Left"
                   Width="40"
                   Height="40"
                   Tag="{Binding ProductBarcode}"
                   Cursor="Hand"
                   MouseDown="img_MouseDown">
                <Image.Style>
                    <Style TargetType="{x:Type Image}">
                        <Setter Property="Source" Value="/Resources/edit_button.png" />
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Source" Value="/Resources/edit_button_hovered.png" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Image.Style>
            </Image>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

I can't fire the event in the Image control. The one that is firing is the event in the ListViewItem . How to access the event in the Image control?

Here are the events:

private void img_MouseDown(object sender, MouseButtonEventArgs e)
{
    switch ((sender as Image).Name)
    {
        case "imgEdit":
            MessageBox.Show("EDIT");
            break;
        default:
            break;
    }
}
private void listViewItem_MouseDown(object sender, RoutedEventArgs e)
{
    MessageBox.Show("ROW CLICKED");
}

The PreviewMouseDown event of the ListViewItem will always be raised before the MouseDown event of the Image. This is how routed events work: https://msdn.microsoft.com/en-us/library/ms742806(v=vs.110).aspx . PreviewMouseDown is a tunneling event and MouseDown is a bubbling event.

If you don't want to handle the PreviewMouseDown event when the Image is clicked you could check the type of the OriginalSource of the RoutedEventArgs and return immediately from the event handler if it is Image :

private void listViewItem_MouseDown(object sender, RoutedEventArgs e)
{
    if (e.OriginalSource is Image)
        return; // do nothing

    MessageBox.Show("ROW CLICKED");
}

Try:

private void listViewItem_MouseDown(object sender, MouseButtonEventArgs e)
{
    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
    {
        MessageBox.Show("ROW CLICKED");
    }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM