How do I correctly set the duration for a WPF TextBlock DoubleAnimation to maintain the same speed when the text length varies when changed?

How do I correctly set the duration for a WPF TextBlock DoubleAnimation to maintain the same speed when the text length varies when changed?

So in the code below, the marquee runs to complete the entire string of text once. On the completed event, the text changes, which simulates when the feed would change. The marquee is then restarted.

However, the duration for the DoubleAnimation needs to maintain a constant speed, irrespective of the string length of the text content.

How do I correctly calculate this?

It’s not as simple as a value for 1 character * the text length.

I have tried looking this up but have not found an answer to this.

Any help greately appreciated.

Here is all the code…

The xaml – MainWindow.xaml:

<Window x:Name="MainWin" x:Class="MarqueeWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        
        xmlns:local="clr-namespace:MarqueeWPF"
        mc:Ignorable="d"
        Title="" Height="35" Width="800"
        Background="#404040"
        ResizeMode="NoResize"
        AllowsTransparency="False"
        WindowStyle="None"
        Topmost="false"
        Left="0"
        Top="0"
        Foreground="WhiteSmoke"
        FontFamily="Ariel"
        FontSize="12"
        
        ShowInTaskbar="False"
        WindowStartupLocation="Manual"
        WindowState="Normal"
        MaxHeight="36"
        Loaded="_onLoaded"
        Closing="_onClosing"
        
        >

    <Canvas ClipToBounds="False"
                 Name="canMain"
                 MaxHeight="35"         
                 Background="#303030"
                 
                 Height="35">
        <TextBlock  Name="tbmarquee" 
                        Text="Shrek 5: Mike Myers, Eddie Murphy and Cameron Diaz to return for new film - BBC.com | Ben Affleck's daughter Violet reveals why she wears face mask in public in sad admission - The Mirror | Dinosaur unearthed on Isle of Wight identified as new plant-eating species - The Guardian | Keir Starmer says defence spending commitment 'cast iron' - but refuses to give timeline - BBC.com | Two children from Liverpool primary school dealing with infection outbreak have died - Sky News | England vs Netherlands LIVE: Updates and team news ahead of Euro 2024 semi-final - The Independent | Almost half Tory members want merger with Reform UK, poll suggests, as leadership infighting escalates – UK politics live - The Guardian | Samsung Electronics workers to extend strike indefinitely - The Guardian | Hip-hop band Cypress Hill makes 1996 Simpsons joke come true - The Guardian | Police search for man after three women killed in Bushey - The Guardian | Israel-Hamas war: Dozens killed in Israeli airstrike outside school in Gaza - Sky News | Barratt shares drop as it warns it will build fewer homes this year; Britons spend on days out over DIY – business live - The Guardian | Sugar tax cut adult intake by two teaspoons a day - The Times | Kylian Mbappe issues damning verdict on France 'failure' after Euro 2024 howler - The Mirror | Nick Kyrgios comes up with brilliant new nickname for Daniil Medvedev at Wimbledon - Express | Jay Slater's family break silence after Tenerife police say he is NOT ‘missing feared dead’ -Birmingham Live | New FLiRT Covid variant spreading across the UK as doctors issue summer warning - The Independent | New Manchester United bid incoming, Ineos are determined to land Erik ten Hag's key target - United In Focus - Manchester United FC News | Type of Russian missile that struck Kyiv children’s hospital uses western components - Financial Times | How Le Pen’s far right blew it - POLITICO Europe "
                            FontSize="18"
                            FontFamily="Ariel"
                            FontWeight="Normal"
                            Foreground="WhiteSmoke" 
                            
                            RenderOptions.BitmapScalingMode="HighQuality" 
                            Canvas.Top="2"></TextBlock>
    </Canvas>
    
</Window>

The code-behind – MainWindow.xaml.cs:

using System.Diagnostics;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using Newtonsoft.Json.Linq;
using System.Windows.Media.Animation;

namespace MarqueeWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private double _marqueeTimeInSeconds = 40;
        private string _testText = "";
        private int _completedCount;

        public MainWindow()
        {
            InitializeComponent();

            Width = SystemParameters.PrimaryScreenWidth;
            Top = 0;
        }

        private void _onLoaded(object sender, RoutedEventArgs e)
        {
            _testText = "Shrek 5: Mike Myers, Eddie Murphy and Cameron Diaz to return for new film - BBC.com | Ben Affleck's daughter Violet reveals why she wears face mask in public in sad admission - The Mirror | Dinosaur unearthed on Isle of Wight identified as new plant-eating species - The Guardian | Keir Starmer says defence spending commitment 'cast iron' - but refuses to give timeline - BBC.com | Two children from Liverpool primary school dealing with infection outbreak have died - Sky News | England vs Netherlands LIVE: Updates and team news ahead of Euro 2024 semi-final - The Independent | Almost half Tory members want merger with Reform UK, poll suggests, as leadership infighting escalates – UK politics live - The Guardian | Samsung Electronics workers to extend strike indefinitely - The Guardian | Hip-hop band Cypress Hill makes 1996 Simpsons joke come true - The Guardian | Police search for man after three women killed in Bushey - The Guardian | Israel-Hamas war: Dozens killed in Israeli airstrike outside school in Gaza - Sky News | Barratt shares drop as it warns it will build fewer homes this year; Britons spend on days out over DIY – business live - The Guardian | Sugar tax cut adult intake by two teaspoons a day - The Times | Kylian Mbappe issues damning verdict on France 'failure' after Euro 2024 howler - The Mirror | Nick Kyrgios comes up with brilliant new nickname for Daniil Medvedev at Wimbledon - Express | Jay Slater's family break silence after Tenerife police say he is NOT ‘missing feared dead’ -Birmingham Live | New FLiRT Covid variant spreading across the UK as doctors issue summer warning - The Independent | New Manchester United bid incoming, Ineos are determined to land Erik ten Hag's key target - United In Focus - Manchester United FC News | Type of Russian missile that struck Kyiv children’s hospital uses western components - Financial Times | How Le Pen’s far right blew it - POLITICO Europe ";

            tbmarquee.Text = _testText;
            tbmarquee.UpdateLayout();
            
            _marqueeTimeInSeconds = 5; // secs; // 160;

            Canvas.SetRight(canMain, SystemParameters.PrimaryScreenWidth);

            RightToLeftMarquee();
        }
        
        private void _onClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
        }

        private void RightToLeftMarquee()
        {
            tbmarquee.Text = _testText;
            tbmarquee.UpdateLayout();

            DoubleAnimation doubleAnimation = new DoubleAnimation();
            doubleAnimation.Completed += _doubleAnimation_Completed;
            double height = canMain.ActualHeight - tbmarquee.ActualHeight;
            tbmarquee.Margin = new Thickness(0, height / 2, 0, 0);
            
            doubleAnimation.From = -tbmarquee.ActualWidth;
            doubleAnimation.To = canMain.ActualWidth;
            //doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
            
            doubleAnimation.Duration = new
                    Duration(TimeSpan.FromSeconds(_marqueeTimeInSeconds));
            tbmarquee.BeginAnimation(Canvas.RightProperty, doubleAnimation);
        }

        private void _doubleAnimation_Completed(object? sender, EventArgs e)
        {
            _completedCount++;

            // Change after first complete
            if (_completedCount == 1)
            {
                // comment/uncomment for different test cases
                // 1. reverse text for test purposes
                //_testText = ReverseString(_testText);

                // 2. make text longer for test purposes
                _testText = _testText + _testText.Substring(0, _testText.Length / 2);

                // 3. make text much longer for test purposes
                //_testText = _testText + _testText + _testText + _testText + _testText + _testText  + _testText + _testText + _testText + _testText + _testText;

                // 4. make text shorter for test purposes
                //_testText = _testText.Substring(0, _testText.Length / 2);

                // 5. one character test
                // _testText = _testText[..1];

                _marqueeTimeInSeconds = 450; // ???? How to calculate this?

                RightToLeftMarquee();
            }
        }

        private string ReverseString(string text)
        {
            var a = text.ToCharArray();
            Array.Reverse(a);
            var result = new string(a);
            return result;
        }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật