提出问题提出问题
 

已答复Marquee / Scrolling Text

  • 2006年10月30日 7:07Sai A 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
    Hi,
    Is it possible to create a marque or scrolling text in WPF. One approach I can think of is by using timers and doing it programatically. Is there any other approach?

    Thanks
    Sai

答案

  • 2006年10月30日 8:24Douglas Stockwell 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     已答复

    You can use animations. Here's an example:

    However, the hardcoded Width and From/To may pose a problem. Depending on where this is used, you can probably work around this by applying bindings on the inital TranslateTrasform.X and the To of the DoubleAnimation.

    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Grid Width="300" ClipToBounds="True">
            <TextBlock>
                <TextBlock.RenderTransform>
                    <TranslateTransform x:Name="translate" />
                </TextBlock.RenderTransform>
                <TextBlock.Triggers>
                    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                        <BeginStoryboard>
                            <Storyboard RepeatBehavior="Forever">
                                <DoubleAnimation 
                                    From="300" To="-300" 
                                    Storyboard.TargetName="translate" 
                                    Storyboard.TargetProperty="X"
                                    Duration="0:0:5" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </TextBlock.Triggers>
                Is it possible to create a marque or scrolling text in WPF?
            </TextBlock>
        </Grid>
    </Page>

    - Doug

  • 2006年11月1日 1:59LesterLobo - MSFT版主用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     已答复

    yeah, check out the double animation topic in the SDK.... it should provide some sample code.

    HTH

全部回复

  • 2006年10月30日 8:24Douglas Stockwell 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     已答复

    You can use animations. Here's an example:

    However, the hardcoded Width and From/To may pose a problem. Depending on where this is used, you can probably work around this by applying bindings on the inital TranslateTrasform.X and the To of the DoubleAnimation.

    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Grid Width="300" ClipToBounds="True">
            <TextBlock>
                <TextBlock.RenderTransform>
                    <TranslateTransform x:Name="translate" />
                </TextBlock.RenderTransform>
                <TextBlock.Triggers>
                    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                        <BeginStoryboard>
                            <Storyboard RepeatBehavior="Forever">
                                <DoubleAnimation 
                                    From="300" To="-300" 
                                    Storyboard.TargetName="translate" 
                                    Storyboard.TargetProperty="X"
                                    Duration="0:0:5" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </TextBlock.Triggers>
                Is it possible to create a marque or scrolling text in WPF?
            </TextBlock>
        </Grid>
    </Page>

    - Doug

  • 2006年10月31日 23:20paukp06 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
    I need to change hardcoded Width and From/To at code behind. I need to create a lot of text to display like news ticker. Is it possible to create in code behind?
  • 2006年11月1日 1:59LesterLobo - MSFT版主用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     已答复

    yeah, check out the double animation topic in the SDK.... it should provide some sample code.

    HTH

  • 2007年3月21日 14:23Joao Sousa 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     

    I have a textbox with rss feeds and i need to create some animation so that the text is always srolling, i need some help on how to do that. The textbox lenght must be dynamic...

    Thanks

  • 2007年3月27日 12:18Ishmael 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
    I used the above code, but if i increase the size of the font or change the text to a bigger text, when animating it always clips the textbox. why?
  • 2007年3月28日 12:10Douglas Stockwell 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     建议的答复

    Ishmael: As I mentioned above the code uses fixed size values.

     

    Here's a more generic solution. This uses my JScriptConverter to make a few small calculations, the source is available here (http://11011.net/archives/000668.html)

    <Window x:Class="Marquee.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:utils="clr-namespace:Utils.Avalon">
      <Window.Resources>
        <utils:JScriptConverter x:Key="JScript" />
        <ControlTemplate TargetType="ContentControl" x:Key="Marquee">
          <Canvas ClipToBounds="True" Name="container">
            <Grid Name="marquee">
              <Grid.RenderTransform>
                <TranslateTransform x:Name="translate">
                  <TranslateTransform.X>
                    <MultiBinding Converter="{StaticResource JScript}"
                                  ConverterParameter="values[0] + values[1]">
                      <Binding ElementName="container" Path="ActualWidth" />
                      <Binding ElementName="content" Path="ActualWidth" />
                    </MultiBinding>
                  </TranslateTransform.X>
                </TranslateTransform>
              </Grid.RenderTransform>
              <ContentPresenter Name="content">
                <ContentPresenter.RenderTransform>
                  <TranslateTransform>
                    <TranslateTransform.X>
                      <Binding Path="ActualWidth"
                               ElementName="content"
                               Converter="{StaticResource JScript}"
                               ConverterParameter="-values[0]" />
                    </TranslateTransform.X>
                  </TranslateTransform>
                </ContentPresenter.RenderTransform>
              </ContentPresenter>
            </Grid>
          </Canvas>
          <ControlTemplate.Triggers>
            <EventTrigger RoutedEvent="FrameworkElement.Loaded">
              <BeginStoryboard>
                <Storyboard RepeatBehavior="Forever">
                  <DoubleAnimation To="0"
                                   Storyboard.TargetName="translate"
                                   Storyboard.TargetProperty="X"
                                   Duration="0:0:5" />
                </Storyboard>
              </BeginStoryboard>
            </EventTrigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Window.Resources>
      <ContentControl Template="{StaticResource Marquee}">
        Is it possible to create a marque or scrolling text in WPF?
      </ContentControl>
    </Window>
    • 已建议为答案HDWagner 2008年10月5日 16:26
    •  
  • 2007年3月28日 17:01Ishmael 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
    When i try to use that code and the jscriptconverter, blend tells me it can't create an instance of jscriptconverter. odd that because all the namespace are correct.
  • 2007年11月15日 22:45Juan1111111111 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     

     

    I am having the same problem, we need your help!!!

     

    I have the JScriptConverter.cs inside of a project named util. In another project, named Marquesina, I have the xaml code. Both, inside the same solution.

     

    I am trying to instanciate the JScriptConverter class in the XAML, and I can`t.

     

    Here is the code that I am using:

     

    <Window x:Class="Marquesina.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:utils="util">

     

    <Window.Resources>

    <utils:JScriptConverter x:Key="JScript" />

    <ControlTemplate TargetType="ContentControl" x:Key="Marquee">

    <Canvas ClipToBounds="True" Name="container">

    <Grid Name="marquee">

     

    Do you know what am I doing wrong?

    It is very important that you answer me, I need it asap.

     

    Bye, and many thanks.

    Juan

  • 2007年11月28日 18:38Matt Galbraith - MSFT版主用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     

    Great examples guys, but none of these are usable (even ignoring hard coded width issues) for a real headline scenario.  Just try either of the XAML snippets above and make the text 2 or 3 times as long and you'll see the clipping problem.

     

    Does anyone know how to make this work when the text is wider than the grid?  The content is automagically clipped to exactly the ActualWidth of the grid.  For a true headline scenario, this isn't very useful... at least on CNN the marquees are routinely much longer than the screen width for a single headline.

     

    I've got this working by animating the Canvas.Left property, since Canvas has no such limitations... as the Left property changes, layout updates and thus changes the text width appropriately. 

     

    (Other thread about this is here: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2475074&SiteID=1&mode=1 )

  • 2007年12月8日 17:24Fanou360 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
    Someone found an elegant solution to display text *** news feed dinamicly and with no hard coded width ?
  • 2008年7月7日 15:55Patrizio 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     包含代码
    This is not a finished code, but my first attempt to make a marquee with WPF ...

    <Window x:Class="IUCliente" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Title="IUCliente" Height="600" Width="800" Background="Black">  
        <Grid> 
            <Grid.RowDefinitions> 
                <RowDefinition Height="24*" /> 
                <RowDefinition Height="120*" /> 
                <RowDefinition Height="268*" /> 
                <RowDefinition Height="94*" /> 
                <RowDefinition Height="56*" /> 
            </Grid.RowDefinitions> 
            <Grid.ColumnDefinitions> 
                <ColumnDefinition Width="572*" /> 
                <ColumnDefinition Width="160*" /> 
                <ColumnDefinition Width="46*" /> 
            </Grid.ColumnDefinitions> 
     
            <Viewbox Grid.Row="3" Name="Viewbox1" Stretch="UniformToFill" StretchDirection="Both" Grid.ColumnSpan="3">  
                <TextBlock  HorizontalAlignment="Left" Margin="0,0,0,0" Name="TextBlock1" Text="Este es un texto muy pero muy pero muy largo" FontFamily="Calibri" FontSize="20" Background="Black" Foreground="AntiqueWhite" VerticalAlignment="Center" TextWrapping="NoWrap"></TextBlock> 
            </Viewbox> 
              
        </Grid> 
    </Window> 
     

    And the code in VB that start de animations is this one, you can bind it to a button or another event ...

            Dim lp As Double = TextBlock1.ActualWidth  
            Dim da As New Windows.Media.Animation.ThicknessAnimation  
     
            da.Duration = New Duration(TimeSpan.Parse("0:0:25"))  
            da.From = New Thickness(lp, 0, -lp, 0)  
            da.To = New Thickness(-lp, 0, lp, 0)  
            da.RepeatBehavior = Windows.Media.Animation.RepeatBehavior.Forever  
     
            TextBlock1.BeginAnimation(TextBlock.MarginProperty, da) 


    I hope this will help you find a way to construct a marquee the way you want
    • 已编辑Patrizio 2008年7月7日 16:03spellchecking
    •  
  • 2008年9月1日 13:46BalaMurugan_Sa 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     包含代码
    Hey guys,

    Check this link.. I have tried in a different way...

    http://forums.expression.microsoft.com/en-US/blend/thread/8fd03c38-438a-44fa-9845-067131041b63

    -BALA.
  • 2008年9月17日 15:06philipsh 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     包含代码
     Here's a solution I came up with.  You basically animate the TranslateTransform of a textblock on a canvas.  The timing is basically y=mx+b stuff (fromSecValue = equSlope * textSize + offSetY) to account for the fact that longer text needs to be given more time to traverse a longer distance.  I've tested it with text up to around 500 chars in length.  Seems to work well and the scroll is very smooth.  Below is the Xaml and at bottom is the code behind.

     

    <Window x:Class="transforms.Window2" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Title="Window2" Height="672" Width="807">  
        <Grid Background="DarkGray">  
            <Canvas Name="canvas1" Height="32" ClipToBounds="True" HorizontalAlignment="Left" VerticalAlignment="Bottom" Background="White" Width="500">  
                <TextBlock Canvas.Left="0" Canvas.Top="0" Height="31" Name="textBlock1" Width="219" Text="Have a nice day!" FontSize="18.6666666666667" TextWrapping="NoWrap" VerticalAlignment="Center">  
                     <TextBlock.RenderTransform> 
               <TransformGroup> 
                <ScaleTransform ScaleX="1" ScaleY="1"/>  
                <SkewTransform AngleX="0" AngleY="0"/>  
                <RotateTransform Angle="0"/>  
                <TranslateTransform x:Name="rtTTransform"/>  
               </TransformGroup> 
              </TextBlock.RenderTransform> 
             </TextBlock>          
            </Canvas> 
            <Button Margin="0,0,53,102.861" Name="button1" Click="button1_Click" Height="88" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="244">Apply</Button> 
        </Grid> 
    </Window> 

     

     private void button1_Click(object sender, RoutedEventArgs e)  
            {  
     
                 
                double textBoxWidth = 10;  
     
                double pixelXFactor;  
                double canvaswidth = this.canvas1.Width;  
                double negXOffSet = 0;  
                double fromSecValue = 0;  
                string theText = "This is the text";  
                double equSlope = 0.022546419;  
                double offSetY = 10.96286472;  
                double stringSize;  
     
                int textLen = theText.Length;  
               
     
                //Set the width of the text box according to the width (not length) of the text in it.  
     
                System.Globalization.CultureInfo enUsCultureInfo;  
                Typeface fontTF;  
                FormattedText frmmtText;  
     
                if (textLen > 0)  
                {  
                    enUsCultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-us");  
                    fontTF = new Typeface(this.textBlock1.FontFamily, this.textBlock1.FontStyle, this.textBlock1.FontWeight, this.textBlock1.FontStretch);  
                    frmmtText = new FormattedText(theText, enUsCultureInfo, FlowDirection.LeftToRight, fontTF, this.textBlock1.FontSize, this.textBlock1.Foreground);  
     
                    stringSize = frmmtText.Width;  
     
                 
                    if (stringSize < 100)  
                        pixelXFactor = 1.02;  
                    else 
                        pixelXFactor = 1.01;  
     
                    textBoxWidth = stringSize * pixelXFactor;  
     
                    this.textBlock1.Width = textBoxWidth;  
                    negXOffSet = textBoxWidth * -1;        
                        
                    fromSecValue = (stringSize * equSlope) + offSetY;             
     
                    this.textBlock1.Text = theText;  
     
                    Storyboard _sb = new Storyboard();  
     
                    Duration durX = new Duration(TimeSpan.FromSeconds(fromSecValue));  
     
                    DoubleAnimation daX = new DoubleAnimation(canvaswidth, negXOffSet, durX);  
                    daX.RepeatBehavior = RepeatBehavior.Forever;  
     
                     
                    Storyboard.SetTargetName(daX, "rtTTransform");  
                    Storyboard.SetTargetProperty(daX, new PropertyPath(TranslateTransform.XProperty));  
     
                    _sb.Children.Add(daX);  
                    _sb.Begin(this.textBlock1);  
                }  
                else 
                {  
                    textBoxWidth = 1;  
                    stringSize = 0;  
                }             
            }  
        }  
    }  
     
  • 2008年9月17日 20:45Litter 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
    Great job!

    Is it possible to update the text dynamically? For example via an RSS Feed?
  • 2008年10月5日 16:47HDWagner 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     包含代码
    Douglas, if you're still reading this ...

    Or all other WPF gods. I used Douglas Stockwells XAML-only solution with minor adjustments:

        <ControlTemplate TargetType="ContentControl" x:Key="MarqueeContentControl">

            <Canvas ClipToBounds="True" Name="container"
                    Height="{Binding ElementName=content, Path=ActualHeight, Mode=OneWay}" >
                <Grid>

                    <Grid.RenderTransform>
                        <TranslateTransform x:Name="marquee_translate">
                            <TranslateTransform.X>
                                <MultiBinding Converter="{StaticResource Add}" Mode="OneWay">
                                    <Binding ElementName="container" Path="ActualWidth" Mode="OneWay" />
                                    <Binding ElementName="content" Path="ActualWidth" Mode="OneWay" />
                                </MultiBinding>
                            </TranslateTransform.X>
                        </TranslateTransform>
                    </Grid.RenderTransform>

                    <ContentPresenter Name="content">
                        <ContentPresenter.RenderTransform>
                            <TranslateTransform>
                                <TranslateTransform.X>
                                    <MultiBinding Mode="OneWay" Converter="{StaticResource Substract}">
                                        <Binding Mode="OneTime">
                                            <Binding.Source>
                                                <s:Double>0</s:Double>
                                            </Binding.Source>
                                        </Binding>
                                        <Binding ElementName="content" Path="ActualWidth" Mode="OneWay"/>
                                    </MultiBinding>
                                </TranslateTransform.X>
                            </TranslateTransform>
                        </ContentPresenter.RenderTransform>
                    </ContentPresenter>

                </Grid>
            </Canvas>

            <ControlTemplate.Triggers>
                <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                    <BeginStoryboard>
                        <Storyboard RepeatBehavior="Forever">
                            <DoubleAnimation
                                   To="0"
                                   Storyboard.TargetName="marquee_translate"
                                   Storyboard.TargetProperty="X"
                                   Duration="0:0:15" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </ControlTemplate.Triggers>

        </ControlTemplate>


    I use it like this in my code:


    <ContentControl Template="{DynamicResource MarqueeContentControl}" VerticalAlignment="Bottom">
       <WPFUI:WPFLabel Style="{DynamicResource front-title-label-style}" Caption="{Binding Path=Data.group_selected_caption}" />
    </ContentControl>



    Works like a charm. But only in about 75 percent of all cases. If I show a Window using this code, there's a certain chance that it crashes and I get the following exception (it translates to something like 'The name marquee-translate can't be found in the name scope of ControlTemplate'):



    System.InvalidOperationException: Der Name "marquee_translate" kann im Namensbereich von "System.Windows.Controls.ControlTemplate" nicht gefunden werden.
       bei System.Windows.Media.Animation.Storyboard.ResolveTargetName(String targetName, INameScope nameScope, DependencyObject element)
       bei System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
       bei System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
       bei System.Windows.Media.Animation.Storyboard.BeginCommon(DependencyObject containingObject, INameScope nameScope, HandoffBehavior handoffBehavior, Boolean isControllable, Int64 layer)
       bei System.Windows.Media.Animation.BeginStoryboard.Begin(DependencyObject targetObject, INameScope nameScope, Int64 layer)
       bei System.Windows.Media.Animation.BeginStoryboard.Invoke(FrameworkElement fe, FrameworkContentElement fce, Style targetStyle, FrameworkTemplate frameworkTemplate, Int64 layer)
       bei System.Windows.StyleHelper.InvokeEventTriggerActions(FrameworkElement fe, FrameworkContentElement fce, Style ownerStyle, FrameworkTemplate frameworkTemplate, Int32 childIndex, RoutedEvent Event)
       bei System.Windows.StyleHelper.ExecuteEventTriggerActionsOnContainer(Object sender, RoutedEventArgs e)
       bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
    ...

    Okay. The Storyboard can't find the TranslateTransform which is defined some lines before. How can this happen? And even more imprtant: How can I avoid this?
  • 2008年11月21日 18:39Ilya Bernex 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     包含代码
    <UserControl x:Class="WpfApplication1.AniLabelControl" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="317"
        <Canvas x:Name="canvas1" ClipToBounds="True" Background="White"
            <TextBlock Canvas.Left="0" Canvas.Top="0" x:Name="textBlock1" TextWrapping="NoWrap" VerticalAlignment="Center">   
                <TextBlock.RenderTransform>  
                    <TransformGroup>  
                        <ScaleTransform ScaleX="1" ScaleY="1"/>   
                        <SkewTransform AngleX="0" AngleY="0"/>   
                        <RotateTransform Angle="0"/>   
                        <TranslateTransform x:Name="rtTTransform"/>   
                    </TransformGroup>  
                </TextBlock.RenderTransform>  
            </TextBlock> 
        </Canvas> 
    </UserControl> 
     


    namespace WpfApplication1 
        public partial class AniLabelControl : UserControl 
        { 
            #region Control Properties 
            public string Text 
            { 
                get { return this.textBlock1.Text; } 
                set { this.textBlock1.Text = value; } 
            } 
            #endregion 
     
            Storyboard _sb = new Storyboard(); 
            public AniLabelControl() 
            { 
                InitializeComponent(); 
                 
            } 
            protected override void  OnRenderSizeChanged(SizeChangedInfo sizeInfo) 
            { 
             base.OnRenderSizeChanged(sizeInfo); 
                 StartAnim(); 
            } 
            private void StartAnim() 
            { 
                if (this.textBlock1.ActualWidth < canvas1.ActualWidth) return; 
                Duration durX = new Duration(TimeSpan.FromSeconds(this.textBlock1.ActualWidth / 60)); 
                DoubleAnimation daX = new DoubleAnimation(0, canvas1.ActualWidth - this.textBlock1.ActualWidth, durX); 
                daX.RepeatBehavior = RepeatBehavior.Forever; 
                Storyboard.SetTargetName(daX, "rtTTransform"); 
                daX.AutoReverse = true
                daX.AccelerationRatio = (double)0.9; 
                Storyboard.SetTargetProperty(daX, new PropertyPath(TranslateTransform.XProperty)); 
                 
                _sb.Children.Add(daX); 
                _sb.Begin(this.textBlock1); 
            } 
        } 

    My version )))


  • 2009年8月7日 8:19Razan 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
  • 2009年11月16日 18:34JorgeMiralles 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     
    Hello Philipsh

    I'm using your code to make a marquee text, but some times works smooth and sometimes jumpy, what can be wrong? I would like a smooth animation always.

    Thanks
    Jorge