[英]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.