使用ObservableCollection仅在单个项目上触发Binding.TargetUpdated

时间:2014-06-21 17:02:28

标签: wpf data-binding observablecollection

我有三个文本块,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?

1 个答案:

答案 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}}