You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中用C#通过Storyboard实现RectangleGeometry动画:PropertyPath路径疑问

在C#中使用Storyboard为RectangleGeometry实现动画的PropertyPath写法

要为RectangleGeometry的Rect属性创建Storyboard动画,PropertyPath的写法由你指定的目标对象决定:

  • 若target是直接获取的RectangleGeometry实例(比如从Image的Clip属性中取出),路径写"Rect"
  • 若target是Image控件(即XAML中的Item),路径写成"Clip.Rect"

修改后的代码示例

场景1:目标为RectangleGeometry实例

// 从Image的Clip中获取RectangleGeometry
var clipGeometry = Item.Clip as RectangleGeometry;

RectAnimation rectAnimation = new RectAnimation
{
    Duration = TimeSpan.FromMilliseconds(toMills - fromMills),
    FillBehavior = FillBehavior.HoldEnd,
    From = new Rect(xFrom, yFrom, wFrom, hFrom),
    To = new Rect(xTo, yTo, wTo, hTo)
};

// 设置动画目标为RectangleGeometry
rectAnimation.SetValue(Storyboard.TargetProperty, clipGeometry);
// 指定属性路径为"Rect"
rectAnimation.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("Rect"));

storyboard.Children.Add(rectAnimation);

场景2:目标为Image控件

RectAnimation rectAnimation = new RectAnimation
{
    Duration = TimeSpan.FromMilliseconds(toMills - fromMills),
    FillBehavior = FillBehavior.HoldEnd,
    From = new Rect(xFrom, yFrom, wFrom, hFrom),
    To = new Rect(xTo, yTo, wTo, hTo)
};

// 设置动画目标为Image控件
rectAnimation.SetValue(Storyboard.TargetProperty, Item);
// 通过属性路径访问Clip下的Rect属性
rectAnimation.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("Clip.Rect"));

storyboard.Children.Add(rectAnimation);

额外扩展:动画ScaleTransform的写法

如果需要对XAML中RectangleGeometry下的ScaleTransform做动画(比如修改ScaleX),对应的PropertyPath:

  • 若目标是ScaleTransform实例:"ScaleX"
  • 若目标是RectangleGeometry实例:"Transform.Children[0].ScaleX"(Transform是TransformGroup,第一个子元素为ScaleTransform)
  • 若目标是Image控件:"Clip.Transform.Children[0].ScaleX"

内容的提问来源于stack exchange,提问作者Andrea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:27:41