我正在制作一个动态歌词播放器,使用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>

The effect of this window is as follows:
enter image description here

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的宽度将非常缓慢而不平滑地变化.我try 过改变DispatcherTimerInterval,或使用DoEvents,但没有任何效果.

请问有什么办法使它更平滑些吗.

推荐答案

try 使用双动画来设置宽度的动画,例如:

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

Csharp相关问答推荐

List T.AddRange在传递ConcurrentDictionary作为参数时引发ArgumentExcellent

无法从具有一对多关系的C#类中使用Swagger创建记录

C#使用属性和值将JSON转换为XML

使用LayoutKind在C#中嵌套 struct .显式

如何注册接口类型,类型<>

更新产品但丢失产品ASP.NET Core的形象

Amazon SP-API确认发货不设置&Quot;递送服务

ASP.NET Core AutoMapper:如何解决错误 CS0121调用在以下方法或属性之间不明确

为什么在使用动态obj+类obj时会调用串联?

如何在.NET AOT中为所有枚举启用JsonStringEnumConverter

将FileStream的特定部分作为字节数组读取

如何在mediatr命令中访问HttpContext而不安装弃用的nuget包

我想根据姓氏按字母顺序对包含150行徽章编号、姓氏、名字、地址等的文件进行排序.e

Visual Studio,Docker容器-容器调用:连接被拒绝

使用DI实例化带有动态参数的服务?

分别切换用于读取和写入的EF核心日志(log)

测试单个对象是否与Func<;T,bool>;匹配

C#LINQ多行条件

异步等待,如何在Windows窗体中使用它们?

无法通过服务控制台启动.NET Core 6.0服务(错误1053)