开发者

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 />
            </Se开发者_如何学编程tter.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 ...
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜