I think, you cant use this way;) because
foreground
is property for all of the text in the
TextBlock
.
My solution:
Create 'Array' of
TextBlock
for example:
TextBlock[] tb = new TextBlock[5];
then create a timer and finally with every tick event, change
foreground
one of array element.
Updated program in XAML:
<Window x:Class="WpfApp_ColourTextBlock.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen">
<Window.Resources>
<System:String x:Key="textBlockName">textBlock0</System:String>
<Storyboard x:Key="Storyboard1">
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="{DynamicResource textBlockName}">
<EasingColorKeyFrame KeyTime="0:0:2.5" Value="Red"/>
<EasingColorKeyFrame KeyTime="0:0:5" Value="Blue"/>
<EasingColorKeyFrame KeyTime="0:0:7.5" Value="Red"/>
<EasingColorKeyFrame KeyTime="0:0:10" Value="White"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Viewbox>
<StackPanel Name="TextBlocks" Orientation="Horizontal">
</StackPanel>
</Viewbox>
</Window>
And code behind in C#:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace WpfApp_ColourTextBlock
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
counter = 0;
foreach (char item in "Hello Word".ToArray())
{
TextBlock tb = new TextBlock();
tb.Name = "textBlock" + counter++;
this.RegisterName(tb.Name, tb);
tb.Text = item.ToString();
tb.Foreground = Brushes.DarkCyan;
TextBlocks.Children.Add(tb);
}
counter = 0;
System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
myDispatcherTimer.Tick += new EventHandler(myDispatcherTimer_Tick);
myDispatcherTimer.Start();
}
int counter;
void myDispatcherTimer_Tick(object sender, EventArgs e)
{
Resources["textBlockName"] = "textBlock" + counter++;
(Resources["Storyboard1"] as Storyboard).Begin();
if (counter >= TextBlocks.Children.Count)
counter = 0;
}
}
}