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

时间:2015-10-21 23:43:12

标签: c# wpf storyboard event-triggers

我正在尝试动态创建在鼠标悬停时放大的图像。我发现此博客文章http://tozon.info/blog/post/2007/10/14/Three-ways-to-make-your-WPF-images-pop-out-on-MouseOver.aspx显示了如何使用Storyboard执行此操作。

看起来非常简单,我已将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>

我已经在C#中创建了Image,Storyboard和RenderTransform(我想),但我不确定如何将故事板添加为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);

1 个答案:

答案 0 :(得分:1)

您可以再创建2个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);

public static void main(String[] args) throws IOException {
    File dictionaryFile = new File("dict.txt");

    // Count the number of lines in the file
    LineNumberReader lnr = new LineNumberReader(new FileReader(dictionaryFile));
    lnr.skip(Long.MAX_VALUE);

    // Instantiate a String[] with the size = number of lines
    String[] dict = new String[lnr.getLineNumber() + 1];
    lnr.close();

    Scanner scanner = new Scanner(dictionaryFile);
    int wordNumber = 0;

    while (scanner.hasNextLine()) {
        String word = scanner.nextLine();
        if (word.length() >= 2 && !(Character.isUpperCase(word.charAt(0)))) {
            dict[wordNumber] = word;
            wordNumber++;
        }
    }
    scanner.close();
}