为程序化创建的TextBlock添加动画时遇TargetProperty解析错误
解决UWP动画错误:无法解析TargetProperty (UIElement.RenderTransform).(CompositeTransform.TranslateY)
问题根源
错误产生的核心原因是:你创建的TextBlock未初始化RenderTransform属性为CompositeTransform实例。XAML动画系统需要目标元素已存在对应的变换对象,才能通过属性路径(UIElement.RenderTransform).(CompositeTransform.TranslateY)定位到要动画的属性。
修复方案
- 在创建
TextBlock时,显式为其RenderTransform赋值CompositeTransform实例 - (可选)添加动画完成事件移除旧元素,避免布局堆积;等待动画完成后再创建下一个元素,匹配需求中的“移出视图后创建下一个”逻辑
修改后的完整代码
await Task.Run(async () => { TextBlock tb = null; foreach (KeyValuePair<string, string> s in things) { await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { TextBlock _txtBlock = new TextBlock() { Text = s.Key, Margin = new Thickness(131, 0, 0, 0), FontSize = 26, Height = 40, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Width = 168, // 关键:初始化RenderTransform为CompositeTransform RenderTransform = new CompositeTransform() }; innerOverlay.Children.Add(_txtBlock); tb = _txtBlock; }); string tested = GetThings(s.Value); if (tested == string.Empty) { MessageDialog failedMsg = new MessageDialog("failed", "problem"); failedMsg.Commands.Add(new UICommand("Exit")); IUICommand command = await failedMsg.ShowAsync(); if (command.Label.Equals("Exit", StringComparison.CurrentCultureIgnoreCase)) { Windows.UI.Xaml.Application.Current.Exit(); } return; } else { await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { var animation = new DoubleAnimation { EnableDependentAnimation = true, To = 40, Duration = new Duration(TimeSpan.FromMilliseconds(500)), }; Storyboard.SetTarget(animation, tb); Storyboard.SetTargetProperty(animation, "(UIElement.RenderTransform).(CompositeTransform.TranslateY)"); var sb = new Storyboard(); sb.Children.Add(animation); // 动画完成后移除旧TextBlock,避免布局混乱 sb.Completed += (sender, e) => { innerOverlay.Children.Remove(tb); }; sb.Begin(); // 等待动画完成再进入下一次循环,保证元素创建顺序 await sb.CompletedTask; }); thingGroup.Add(s.Key, tested); } } });
内容的提问来源于stack exchange,提问作者Safe Usx
相关产品推荐
相关产品推荐

