繁体   English   中英

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

[英]UI performance issue when I try to change the width of the ItemsControl in WPF

我正在使用这个问题的答案中的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>

这个窗口的效果如下:
在此处输入图像描述

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM