我有三个文本块,Text
属性绑定到ObservableCollection
的项目:
<TextBlock Style="{StaticResource FadeInTextBlock}" Text="{Binding Path=CurrentAnswers[0], NotifyOnTargetUpdated=True}" />
<TextBlock Style="{StaticResource FadeInTextBlock}" Text="{Binding Path=CurrentAnswers[1], NotifyOnTargetUpdated=True}" />
<TextBlock Style="{StaticResource FadeInTextBlock}" Text="{Binding Path=CurrentAnswers[2], NotifyOnTargetUpdated=True}" />
已实施INotifyPropertyChanged
的媒体资源:
public ObservableCollection<Answer> CurrentAnswers
{
get { return currentAnswers; }
set { currentAnswers = value; RaisePropertyChanged("CurrentAnswers"); }
}
每个Textblock使用相同的样式,其中包含Binding.TargetUpdated
事件的触发器,该事件在实际文本中淡出:
<Style x:Key="FadeInTextBlockTwo" TargetType="TextBlock">
<Style.Triggers>
<EventTrigger RoutedEvent="Binding.TargetUpdated">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:0" To="0.0"/>
<DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:1" From="0.0" To="1.0" BeginTime="0:0:0"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
当我在ObservableCollection
中更改一个项目时,所有文本块都会触发事件并执行淡入淡出:
CurrentAnswer[1] = "New Text";
// Textblock 1 - 3 do the fade in animation,
// even if only Textblock 2 has been updated
如何将动画限制为仅更新了绑定值的Textblock?
答案 0 :(得分:1)
当您使用索引绑定到集合的索引器属性并且UI不知道哪个索引已更改时,只会通知索引器属性已更改而未指定索引,因此,在您的情况下,它会刷新所有索引3 TextBlocks
提出TargetUpdated
事件。发生的情况是ObservableCollection
引发PropertyChanged
事件,Binding.IndexerName
作为属性名称。要解决您的问题而不是使用3 TextBlocks
,您可以使用ItemsControl
<ItemsControl ItemsSource="{Binding CurrentAnswers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Style="{StaticResource FadeInTextBlock}" Text="{Binding NotifyOnTargetUpdated=True}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这会在TextBlock
CurrentAnswers
一样多的时间重复{{1}}