如下所示,我想将TargetName设置为movingImage,以便图像从左到右穿过屏幕。 Visual Studio引发错误,不知道如何正确引用它。我想将图像保存在资源字典中,并根据需要以编程方式引入。
我有以下资源:
<Canvas.Resources>
<Storyboard x:Key="myStory">
<DoubleAnimation Storyboard.TargetName="movingImage"
Storyboard.TargetProperty="(Canvas.Left)"
Duration="0:0:5"
From="-157"
To="78"/>
</Storyboard>
<Image x:Key="movingImage"
Canvas.Left="-157"
Source="Resource\myImage.png"/>
</Canvas.Resources>
并在MainWindow.xaml.cs中将Storyboard和Image带入如下:
myCanvas.Children.Add(myCanvas.FindResource("movingImage") as UIElement);
sb = myCanvas.FindResource("myStory") as Storyboard;
sb.Begin();
我得到的错误是:
未处理的类型&#39; System.InvalidOperationException&#39;发生在PresentationFramework.dll
中其他信息:&#39; movingImage&#39;名称在中找不到 名称范围&#39; System.Windows.Controls.Canvas&#39;。
答案 0 :(得分:-1)
进行以下更改:
将图像控件的键更改为movingImageKey
,并命名为movingImage
。
<Image x:Key="movingImageKey" x:Name="movingImage"
Canvas.Left="-157"
Source="Penguins.jpg"/>
代码:
NameScope.SetNameScope(myCanvas, new NameScope());
Image img = (myCanvas.FindResource("movingImageKey") as Image);
myCanvas.RegisterName(img.Name, img);
myCanvas.Children.Add(img);
Storyboard sb = myCanvas.FindResource("myStory") as Storyboard;
sb.Begin();