我正在使用此 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>
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);
关于c# - 当我尝试更改 WPF 中 ItemsControl 的宽度时出现 UI 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72711148/