在c#中,我如何动态地在图像上创建触发器

本文关键字:图像 触发器 创建 动态 何动态 | 更新日期: 2023-09-27 18:18:54

我正在尝试动态创建图像,当您将鼠标放在它们上面时将放大。我找到了一篇博客文章http://tozon.info/blog/post/2007/10/14/Three-ways-to-make-your-WPF-images-pop-out-on-MouseOver.aspx,它展示了如何使用故事板来做到这一点。

它看起来很直接,我已经将StoryBoard xaml添加到App.xaml

现在我需要弄清楚如何将它们添加到我在c#中构建的图像中

要创建的xaml看起来像这样

<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>

我有图像,故事板和RenderTransform创建在c#(我认为),但我不确定如何添加故事板作为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);

在c#中,我如何动态地在图像上创建触发器

可以再创建2个EventTrigger,然后正常添加到Triggers

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);