如果使用Dispatcher.BeginInvoke,仅使用Invoke,使用DataContext.ValueChanged触发器不起作用

时间:2015-06-05 15:51:32

标签: wpf multithreading animation dispatcher

这让我发疯了。我在TextBlock上(在DataGrid中)有以下动画:

<TextBlock.Style>
    <Style TargetType="TextBlock" >
        <Style.Triggers>
            <DataTrigger Binding="{Binding DataContext.ValueChanged, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type xcdg:DataCell}}}" Value="True">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard >
                            <ColorAnimation AutoReverse="True" From="{StaticResource NormalForeground}" To="{StaticResource ModifiedForeground}" Duration="0:0:0.25" Storyboard.TargetProperty="Foreground.Color" FillBehavior="Stop" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

值更新来自另一个线程,因此我正在使用Dispatcher。如果我使用:

更新值
Application.Current.Dispatcher.Invoke(propertychange notification of the viewmodel)

一切正常。如果我使用:

更新值
Application.Current.Dispatcher.BeginInvoke(propertychange notification of the viewmodel)

动画不再有用......任何想法?

1 个答案:

答案 0 :(得分:0)

我会说BeginInvoke几乎被折旧了,转而支持.NET 4.5中引入的异步/等待样式编码。

Begin开头的函数通常使用.NET 1.1中引入的旧的异步样式编写,在我看来,与使用较新的async / await样式相比,它看起来很笨拙。

您可以轻松区分各种风格:

  • .NET 1.1中引入的旧异步函数通常以字母Begin-开头。
  • 与.NET 4.5中引入的async / await样式兼容的较新函数通常以字母-Async结尾。

如果你真的想使用异步调用,请将它基于async / await,并使用类似的东西:

Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });

我建议阅读async / await,这是编写快速,快速,响应迅速的用户应用程序的最佳方式。如果您使用的是Windows 8.1,那么这是唯一的方法,就像您花费超过50毫秒来阻止GUI线程一样,操作系统会抱怨。