如何使用 TargetName 在故事板中使用资源
how to use a resource in a storyboard using TargetName
如下所示,我想将 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();
我得到的错误是:
An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: 'movingImage' name cannot be found in the
name scope of 'System.Windows.Controls.Canvas'.
做这些改变:
将图像控件的键更改为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();
如下所示,我想将 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();
我得到的错误是:
An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: 'movingImage' name cannot be found in the name scope of 'System.Windows.Controls.Canvas'.
做这些改变:
将图像控件的键更改为
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();