好的,我遇到了一件真的让我措手不及的事情。
我正在帮助一位开发者解决几个无关的问题,在他的项目中,他将一些文本动画化到了 TextBlock 中。于是,我回到我的桌子上重新创建了这个项目(为了回答他的问题),但我不小心使用了 TextBox 而不是 TextBlock。我的文本根本没有动画效果!(我真是太没用了!)
最终,我发现他的 xaml 使用的是 TextBlock,而我的使用的是 TextBox。有趣的是,当我使用 TextBox 时,Blend 没有创建关键帧。因此,我在 Blend 中使用 TextBlock 成功让它工作,然后手动修改了 xaml,将 TextBlock 转换为 TextBox。当我运行项目时,出现了以下错误:
InvalidOperationException: '(0)' Storyboard.TargetProperty path contains nonanimatable property 'Text'.
好吧,看来 Blend 足够聪明,知道这一点...并且不会在动画中生成关键帧(它只会直接修改 TextBox 上的值)。+1 给 Blend。
因此,问题变成了:为什么不能对 TextBox.Text 进行动画处理?通常的答案是,您要动画处理的特定属性不是一个 DependencyProperty。但这不是事实,TextBox.Text 是 DependencyProperty。
所以,现在我感到困惑了!为什么不能对 TextBox.Text 进行动画处理呢?
让我用一些 xaml 来说明问题。以下 xaml 可以工作...但使用的是 TextBlock(s)。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="TextBoxTextQuestion.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640"
Height="480"
>
<Window.Resources>
<Storyboard x:Key="animateTextStoryboard">
<StringAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBlock.Text)" Storyboard.TargetName="textControl">
<DiscreteStringKeyFrame KeyTime="0:0:1" Value="Goodbye"/>
</StringAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource animateTextStoryboard}"/>
</EventTrigger>
</Window.Triggers>
<Grid x:Name="LayoutRoot">
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock x:Name="textControl" Text="Hello" FontFamily="Calibri" FontSize="32"/>
<TextBlock Text="World!" Margin="0,25,0,0" FontFamily="Calibri" FontSize="32"/>
</StackPanel>
</Grid>
</Window>
以下 XAML 代码无法正常工作,并使用了 TextBox.Text:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="TextBoxTextQuestion.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640"
Height="480"
>
<Window.Resources>
<Storyboard x:Key="animateTextStoryboard">
<StringAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBox.Text)" Storyboard.TargetName="textControl">
<DiscreteStringKeyFrame KeyTime="0:0:1" Value="Goodbye"/>
</StringAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource animateTextStoryboard}"/>
</EventTrigger>
</Window.Triggers>
<Grid x:Name="LayoutRoot">
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox x:Name="textControl" Text="Hello" FontFamily="Calibri" FontSize="32"/>
<TextBox Text="World!" Margin="0,25,0,0" FontFamily="Calibri" FontSize="32"/>
</StackPanel>
</Grid>
</Window>