简体   繁体   中英

How can I create a WPF style so all Image controls have a MouseDown(click) event on it?

Since the Image control doesn't have a Click event, I simulate it using MouseDown event and it works exactly like a Click.

Here's my style:

 <Window.Resources>
    <Style x:Key="imageStyle" TargetType="{x:Type Image}">
        <Setter Property="RenderTransform">
            <Setter.Value>
                <ScaleTransform />
            </Setter.Value>
        </Setter>
        <Setter Property="RenderTransformOrigin" Value="0.5, 0.5" />
        <Style.Triggers>
            <EventTrigger RoutedEvent="Image.MouseEnter">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Duration="0:0:0.5" From="1" To="1.2" AutoReverse="True"
                                 Storyboard.TargetProperty="RenderTransform.ScaleX"/>
                        <DoubleAnimation Duration="0:0:0.2" From="1" To="1.2" AutoReverse="True" 
                                 Storyboard.TargetProperty="RenderTransform.ScaleY"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

Where/how can I create a click event so I don't have to do this to EVERY SINGLE IMAGE on my Form:

You can use an EventSetter :

<EventSetter Event="MouseClick" Handler="image_Click"/>

And in code-behind :

private void image_Click(object sender, MouseButtonEventArgs e)
{
    Image image = sender as Image;
    if (image != null)
    {
        // do something with the image
    }
}

You could use an EventSetter as Thomas describes, or you could simply catch the tunneling PreviewMouseLeftButtonDown event at the Window level and check if an Image was clicked.

To use PreviewMouseLeftButtonDown to do something for all Images in your application, just add this to your top level Window :

protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
  if(e.Source is Image)
  {
    // ... whatever you want to do when an image is 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