动画WPF数据网格被选中,造成内存泄漏

本文关键字:内存 泄漏 数据 WPF 数据网 网格 动画 | 更新日期: 2023-09-27 18:12:19

我有一个WPF应用程序,我有4行数据网格。我有一个DataTrigger来使用BeginStoryBoard动画选择。每次选择更改都会创建一个内存泄漏堆。这太奇怪了。

<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="True">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Width" Storyboard.TargetName="valueTextBlock" 
                                                       To="375" FillBehavior="HoldEnd" BeginTime="00:00:00.0" Duration="00:00:00.4"></DoubleAnimation>
                            <DoubleAnimation Storyboard.TargetProperty="Width" Storyboard.TargetName="valueTextBlock"
                                                       To="375" FillBehavior="HoldEnd" BeginTime="00:00:00.0" Duration="00:00:00.4"></DoubleAnimation>
                            <DoubleAnimation Storyboard.TargetProperty="Opacity" Storyboard.TargetName="valueTextBlock" 
                                                       To="1" FillBehavior="HoldEnd" BeginTime="00:00:00.0" Duration="00:00:00.4"></DoubleAnimation>
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
                <DataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Width" Storyboard.TargetName="valueTextBlock"
                                                       To="300" FillBehavior="HoldEnd" BeginTime="00:00:00.0" Duration="00:00:00.4"></DoubleAnimation>
                            <DoubleAnimation Storyboard.TargetProperty="Width" Storyboard.TargetName="valueTextBlock"
                                                       To="300" FillBehavior="HoldEnd" BeginTime="00:00:00.0" Duration="00:00:00.4"></DoubleAnimation>
                            <DoubleAnimation Storyboard.TargetProperty="Opacity" Storyboard.TargetName="valueTextBlock" 
                                                       To="0.5" FillBehavior="HoldEnd" BeginTime="00:00:00.0" Duration="00:00:00.4"></DoubleAnimation>
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.ExitActions>
                <DataTrigger.Setters>
                    <Setter Property="BorderBrush" Value="{StaticResource brushTextBox_Border_Focused}" TargetName="valueTextBlock" />
                </DataTrigger.Setters>
            </DataTrigger>

这是在DataTemplate上完成的。Storyboard也被添加到DataGridCell样式中当行被选中时增加字体大小。我敢肯定,我做动画的方式不对。但是当我尝试使用RemoveStoryBoard时,动画并不流畅。

动画WPF数据网格被选中,造成内存泄漏

我找到了一个解决方案,你必须调用垃圾收集器,因为故事板有一个大bug。在加载"imagen":

之前试试这个
GC.Collect();
GC.WaitForPendingFinalizers();