c# - 当我尝试更改 WPF 中 ItemsControl 的宽度时出现 UI 性能问题

标签 c# wpf

我正在使用此 question 的答案中的 ItemsControl 制作动态歌词播放器。 .

我使用两个彼此堆叠的ItemsControls,并且都放置在不同的Canvas中(以获取当前显示的文本的实际宽度), Canvas 放置在 Grid 中,以确保 Canvas 将出现在窗口中的正确位置,如下所示:

<Grid>
    <Canvas x:Name="MainBackLineCanvas" Grid.Column="0" Grid.Row="0">
        <ItemsControl x:Name="MainBackLine" ItemsSource="{Binding}">
        ...
        </ItemsControl>
    </<Canvas>
    <Canvas x:Name="MainColorLineCanvas" Grid.Column="0" Grid.Row="0">
        <ItemsControl x:Name="MainColorLine" ItemsSource="{Binding}">
        ...
        </ItemsControl>
    </Canvas>
</Grid>

该窗口效果如下:
enter image description here

MainBackLine(蓝色文本)将在开始时完全显示,MainColorLine(黄色文本)的宽度在开始时设置为0,并且宽度会随着歌曲时间的增加而增加。

我使用了 DispatcherTimer 来更改其宽度。我的代码如下:

DispatcherTimer TextFlashTimer = new DispatcherTimer();
TextFlashTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
TextFlashTimer.Tick += TextFlash;

private void TextFlash(object? sender, EventArgs e)
{
    //playTimePercent is the percentage of the playback progress of the current sentence, which is a Double variable
    MainColorLine.Width = ((playTimePercent > 0 && playTimePercent <1) ? playTimePercent : 1) * MainBackLine.ActualWidth;
}

当我运行此代码时,MainColorLine 的宽度将非常缓慢且不平滑地变化。我尝试更改 DispatcherTimerInterval,或使用 DoEvents,但没有任何效果。

请问有什么办法可以让它更流畅吗?

最佳答案

尝试使用 DoubleAnimation 来设置宽度动画,例如:

double width = ((playTimePercent > 0 && playTimePercent < 1) ? playTimePercent : 1) * MainBackLine.ActualWidth;
DoubleAnimation doubleAnimation = new DoubleAnimation(width, new Duration(TimeSpan.FromMilliseconds(100)));
MainColorLine.BeginAnimation(FrameworkElement.WidthProperty, doubleAnimation);

关于c# - 当我尝试更改 WPF 中 ItemsControl 的宽度时出现 UI 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72711148/

相关文章:

c# - 用于检查数据库中是否存在实体的 FluentValidator 扩展方法

c# - 如何更改 EmguCV 中的反转帧?

c# - 如何在wpf datagrid中组合多个标题

c# - 如何在 C# XML 注释中链接/分组重载?

c# - 如何通过一次调用 DateTime.ParseExact 来接受两位数和四位数的年份?

c# - 更新绘图而不删除上一张绘图

c# - 克隆 WPF 控件和对象层次结构

c# - 如何关闭 WPF 形状中的抗锯齿?

c# - 使用 Expression Blend SDK 行为破坏 Visual Studio 设计器

c# - 将文本框值传递给类,然后跨页面绑定(bind)值