在C#代码隐藏中动态更改情节提要(在XAML中创建)的属性
本文关键字:属性 XAML 创建 代码 隐藏 动态 | 更新日期: 2023-09-27 18:24:56
我承认我是Silverlight的新手,但你必须从某个地方开始。
这是我的问题:我有XAML代码,它创建了一个画布用于我的网页。我动态地(在后面的代码中)创建了24个较小的画布对象(称为瓦片),并且可以在较大的画布中正确地定位和移动这些瓦片。我现在想为瓷砖的移动设置动画,而不是让它们从一个位置"跳"到下一个位置。在XAML中,我为其中一个瓦片创建了一个情节板和一个DoubleAnimation。单击DoubleAnimation/Storyboard中命名的特定磁贴可以生成正确的动画。现在,我希望能够通过代码背后的代码动态地更改XAML中动画的属性。具体来说,我想更改"From"、"to"、"Storyboard.TargetName"answers"Storybard.TargetProperty"值。这将允许我使用单个动画来控制所有24个瓦片的移动(一次一个)。下面是XAML,下面是我试图正确工作的代码。
XAML
<Canvas x:Name="LayoutRoot" Background="BlanchedAlmond" Height="700" Width="1405">
<Image Source="bkcolor.png" Canvas.Left="600" Height="500" Width="500" Stretch="UniformToFill" Canvas.Top="100"></Image>
<Canvas x:Name="myContainer" Canvas.Left = "50" Canvas.Top="100">
<!---->
<Canvas.Resources>
<Storyboard x:Name="MoveTileAnimation">
<DoubleAnimation x:Name="myDoubleAnimation"
From="400" To="300"
Duration="00:00:1"
Storyboard.TargetName="Tile23"
Storyboard.TargetProperty="(Canvas.Top)">
<DoubleAnimation.EasingFunction>
<PowerEase Power="3" EasingMode="EaseInOut" />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</Canvas.Resources>
<!---->
</Canvas>
</Canvas>
代码隐藏中的C#代码
private void MainPage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Canvas c = sender as Canvas;
// New location is specified by nx, ny
int nx = 200;
int ny = 300;
// Old Location
int ox = 200;
int oy = 200;
// "Tile Moves Up" -- Other case removed for clarity
//----------------------------------------------
// Code below is known to work correctly
//----------------------------------------------
// Set the "To" and "From" properties
myDoubleAnimation.From = Convert.ToDouble(oy);
myDoubleAnimation.To = Convert.ToDouble(ny);
//----------------------------------------------
// Code below does not function correctly
//----------------------------------------------
MoveTileAnimation.SetValue(Storyboard.TargetNameProperty, c.Name); // c.Name is the
// name of the tile
// that was clicked
MoveTileAnimation.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath(Canvas.TopProperty)); // Need to switch between Top and Left
//----------------------------------------------
MoveTileAnimation.Begin(); // This works if the TargetNameProperty in
// the XAML matches the Tile Name
//----------------------------------------------
// Code below is known to work correctly
//----------------------------------------------
// Move the Tile to its new position
tileCanvas[nCanvasID].SetValue(Canvas.TopProperty, Convert.ToDouble(ny));
tileCanvas[nCanvasID].SetValue(Canvas.LeftProperty, Convert.ToDouble(nx));
}
我不想必须创建96个故事板才能在4个方向上移动24个瓦片。如果我可以更改"TargetNameProperty",那么它将减少到4个故事板。如果我也可以更改"TargetPropertyProperty",那么我就不需要一个故事板了。
提前感谢,John
此链接指向一篇文章,其中包含可重用情节串连板的代码。这是一篇老文章,但今天仍然适用——也许这些课程会对你有所帮助。http://www.codeproject.com/Articles/24543/Creating-and-Reusing-Dynamic-Animations-in-Silverl