简体   繁体   中英

In C# how can I dynamically create trigger on an image

I am trying to dynamically create images that will zoom in when you mouse over them. I found this blog post http://tozon.info/blog/post/2007/10/14/Three-ways-to-make-your-WPF-images-pop-out-on-MouseOver.aspx that shows how to do this using Storyboards.

It looks pretty straight forward, and I've added the StoryBoard xaml to App.xaml

Now I need to work out how to add them to the images that I build in C#

The xaml that has to be created looks like this

<Image Source="[Bitmap]" >
    <Image.Triggers>
        <EventTrigger RoutedEvent="Image.MouseEnter" >
            <BeginStoryboard Storyboard="{StaticResource ExpandStoryboard}" />
        </EventTrigger>
        <EventTrigger RoutedEvent="Image.MouseLeave" >
            <BeginStoryboard Storyboard="{StaticResource ShrinkStoryboard}" />
        </EventTrigger>
    </Image.Triggers>
    <Image.RenderTransform>
        <ScaleTransform ScaleX="1" ScaleY="1" />
    </Image.RenderTransform>
</Image>

I've got the Image, the Storyboards and the RenderTransform created in C# (I think), but I'm not sure how to add the storyboards as EventTriggers.

System.Windows.Controls.Image _Image = new System.Windows.Controls.Image();
_Image.Source = this.BitmapToBitmapImage(_Bitmap); // This bit is not really relevant for this question. It works fine though.

ScaleTransform _OriginalScale = new ScaleTransform();
_OriginalScale.ScaleX = 1;
_OriginalScale.ScaleY = 1;

_Image.RenderTransform = _OriginalScale;

Storyboard _ExpandStory = (Storyboard)Application.Current.FindResource("ExpandStoryboard");
Storyboard _ShrinkStory = (Storyboard)Application.Current.FindResource("ShrinkStoryboard");

_Image.Triggers.Add(WHAT GOES HERE);

You can just create 2 more EventTrigger s and add to Triggers normally.

var e1 = new EventTrigger(UIElement.MouseEnterEvent);
//add actions for e1
e1.Actions.Add(new BeginStoryboard{ Storyboard = _ExpandStory});
var e2 = new EventTrigger(UIElement.MouseLeaveEvent);
//add actions for e2
e2.Actions.Add(new BeginStoryboard { Storyboard = _ShrinkStory});
//add the 2 event triggers
_Image.Triggers.Add(e1);
_Image.Triggers.Add(e2);

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