如何为WPF DataGridCell的FontWeight属性添加AnimationClock动画?
嘿,这个问题我之前也踩过坑!你报错的核心原因很简单:FontWeight是一个结构体类型,而你用的DoubleAnimation只能给double类型的属性做动画,类型不兼容肯定会触发错误。下面给你两种简便的实现方法,都能完美满足你“从400(常规)变600(半粗体),3秒后自动恢复”的需求:
方法一:直接用ObjectAnimationUsingKeyFrames(最省心)
这种方法专门针对非数值类型的属性做动画,比如FontWeight这种结构体,直接就能用:
// 创建关键帧动画实例 var fontWeightAnim = new ObjectAnimationUsingKeyFrames(); fontWeightAnim.Duration = TimeSpan.FromSeconds(3); fontWeightAnim.AutoReverse = true; // 自动反向恢复 // 添加起始帧:初始权重400(Regular) fontWeightAnim.KeyFrames.Add(new DiscreteObjectKeyFrame( FontWeight.FromOpenTypeWeight(400), KeyTime.FromTimeSpan(TimeSpan.Zero))); // 添加中间帧:1.5秒时切换到600(SemiBold) fontWeightAnim.KeyFrames.Add(new DiscreteObjectKeyFrame( FontWeight.FromOpenTypeWeight(600), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1.5)))); // 把动画绑定到DataGridCell的FontWeight属性上 dataGridCell.BeginAnimation(DataGridCell.FontWeightProperty, fontWeightAnim);
小提示:如果想要视觉上更平滑的过渡,可以把DiscreteObjectKeyFrame换成LinearObjectKeyFrame,不过字体权重本身是离散的档位,实际效果差异不大~
方法二:用Storyboard包装动画(更灵活)
如果之后你需要把动画和其他效果组合,或者想在XAML里预定义动画,用Storyboard会更方便:
// 先创建关键帧动画 var fontWeightAnim = new ObjectAnimationUsingKeyFrames(); fontWeightAnim.Duration = TimeSpan.FromSeconds(3); fontWeightAnim.AutoReverse = true; fontWeightAnim.KeyFrames.Add(new DiscreteObjectKeyFrame(FontWeight.FromOpenTypeWeight(400), KeyTime.Zero)); fontWeightAnim.KeyFrames.Add(new DiscreteObjectKeyFrame(FontWeight.FromOpenTypeWeight(600), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1.5)))); // 绑定动画目标和属性 Storyboard.SetTarget(fontWeightAnim, dataGridCell); Storyboard.SetTargetProperty(fontWeightAnim, new PropertyPath(DataGridCell.FontWeightProperty)); // 创建并启动故事板 var storyboard = new Storyboard(); storyboard.Children.Add(fontWeightAnim); storyboard.Begin();
再补充一句:你之前尝试的ApplyAnimationClock思路是对的,但选错了动画类型——必须用和FontWeight类型匹配的动画,而ObjectAnimationUsingKeyFrames就是干这个的~
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

