簡體   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