Hi to all,
I have a TextBlock inside a cell of a Grid which I want to animate every time the text changes. My idea is to animate the width property of the TextBlock starting from zero to ActualWidth. As a result, the cell will progressively expand giving a "growing
effect".
XAML:
<Grid MouseEnter="Grid_MouseEnter" Background="Green" HorizontalAlignment="Left" Margin="27,23,0,0" VerticalAlignment="Top"><Grid.ColumnDefinitions><ColumnDefinition Width="20"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><Grid.Triggers><EventTrigger RoutedEvent="MouseLeave"><EventTrigger.Actions><BeginStoryboard><Storyboard Storyboard.TargetName="MyTxt" Storyboard.TargetProperty="Width" ><DoubleAnimation To="0" Duration="0:0:1" /></Storyboard></BeginStoryboard></EventTrigger.Actions></EventTrigger></Grid.Triggers><TextBlock TargetUpdated="MyTxt_TargetUpdated" Tag="{Binding ElementName=MyTxt, Path=ActualWidth, NotifyOnTargetUpdated=True}" Grid.Column="1" Width="0" HorizontalAlignment="Left" Name="MyTxt" VerticalAlignment="Top"><TextBlock.Triggers><EventTrigger RoutedEvent="Binding.TargetUpdated"><EventTrigger.Actions><!--<BeginStoryboard><Storyboard Storyboard.TargetName="MyTxt" Storyboard.TargetProperty="Width" ><DoubleAnimation From="0" To="{Binding ElementName=MyTxt, Path=ActualWidth}" Duration="0:0:1"/></Storyboard></BeginStoryboard>--></EventTrigger.Actions></EventTrigger></TextBlock.Triggers></TextBlock></Grid>
Code behind:
private void Grid_MouseEnter(object sender, MouseEventArgs e) { if (this.MyTxt.Text == "Short content") this.MyTxt.Text = "Looooooooooooong content"; else this.MyTxt.Text = "Short content"; } private void MyTxt_TargetUpdated(object sender, DataTransferEventArgs e) { var txtAnim = new DoubleAnimation(); txtAnim.Duration = new Duration(TimeSpan.FromMilliseconds(1000)); txtAnim.From = 0; txtAnim.To = this.MyTxt.ActualWidth; var sb = new Storyboard(); sb.Children.Add(txtAnim); Storyboard.SetTargetProperty(txtAnim, new PropertyPath(TextBlock.WidthProperty)); Storyboard.SetTarget(txtAnim, this.MyTxt); txtAnim.Freeze(); sb.Begin(); }
Unfortunately it doesn't work: during the first attempt, nothing happens. On the second attempt, the TextBlock animates, but using the ActualWidth of the first execution. On the third attempt, for unknown reasons, the animation enter in an infinite loop.
The animation works as expected if I create and start the Storyboard in code behind (inside the "MyTxt_TargetUpdated" event).
I don't know why this strange behaviour. The storyboard in xaml is the same of the one created in code behind. If it works in code behind, then, it should work also in xaml.
The code above is in "code behind" mode and shows how the animation should be.
To enable "xaml mode" just comment the code inside "MyTxt_TargetUpdated" and uncomment the BeginStoryboard section in the xaml side.
Any help would be appreciated.
Thanks