我想根据ViewModel中的新值为文本框(Price)背景颜色设置动画。
颜色可能因新值而异(大于0 - >绿色 - 小于0 - >红色)
我可以看到的唯一动画是在启动时设置新值。之后,动画将永远不会再出现。
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,178,0,0" TextWrapping="Wrap" Text="{Binding price}" VerticalAlignment="Top" Width="120" x:Name="ChangeField">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding price, Converter={StaticResource formatter}}" Value="positive">
<DataTrigger.EnterActions>
<StopStoryboard BeginStoryboardName="pos"></StopStoryboard>
<BeginStoryboard x:Name="pos">
<Storyboard>
<ColorAnimation AutoReverse="True" To="Green" Duration="0:0:0:0.100" Storyboard.TargetProperty="(TextBox.Background).(SolidColorBrush.Color)"></ColorAnimation>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<RemoveStoryboard BeginStoryboardName="pos"></RemoveStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
价格有可能每秒变化几次,因此我需要在设置新的价格值时中止正在运行的动画。
答案 0 :(得分:1)
对于简单的颜色变化,故事板似乎有些过分。我会绑定背景颜色并为价格创建一个IValueConverter,这只是跟随NotificationChanges for Price。
我建议使用IValueConverter绑定到Price的Background元素并在那里隔离着色逻辑......
<TextBlock x:Name="ChangeField"
Text="{Binding price}"
Background="{Binding price, Converter={StaticResource PriceToColorConverter}}" />
[ValueConversion(typeof(decimal), typeof(Brush))]
public class PriceToColorConverter : IValueConverer
{
public object Convert(object value, Type target)
{
decimal price;
decimal.Parse(value.ToString(), price);
return (price > 0 ? Brushes.Green : Brushes.Red);
}
}
答案 1 :(得分:1)
我想这就是你要找的东西。我测试了它,背景颜色瞬间变化了。基本上你有一个小错误:持续时间应该是hh:mm:ss.fff但你设置hh:mm:ss:??。fff。
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,178,0,0" TextWrapping="Wrap" Text="{Binding price}" VerticalAlignment="Top" Width="120" x:Name="ChangeField">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding price, Converter={StaticResource formatter}}" Value="positive">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation AutoReverse="True" To="Green" Duration="0:0:0.100"
Storyboard.TargetProperty="(TextBox.Background).(SolidColorBrush.Color)"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>