[英]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
的宽度会非常缓慢且不平滑地变化。 我尝试更改DispatcherTimer
的Interval
或使用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.