Reputation: 23
I have a WPF application with a button, that when clicked executes a function that turns the visible property of a TextBlock to Visible:
savetxt.Visibility = Visibility.Visible;
System.Windows.MessageBox.Show(savetxt.Visibility.ToString());
txt.Visibility.ToString()); When the TextBlock turns visible, a storyboard that makes it fade in and out starts:
<TextBlock x:Name="savetxt" Visibility="Hidden" Text="Hello">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="Visibility" Value="Visible">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames BeginTime="0:0:0" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<Visibility>Visible</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation BeginTime="0:0:0.0" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.2"/>
<DoubleAnimation BeginTime="0:0:5.0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
<ObjectAnimationUsingKeyFrames BeginTime="0:0:5.5" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<Visibility>Hidden</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
The first time I press the button, MessageBox.Show shows Visible, and the storyboard starts animating successfully. However, when I press the button the second time, MessageBox.Show shows Hidden and nothing else happens. could anyone help me figure out why savetxt.Visibility = Visibility.Visible; doesn't change the visibility after the first time?
Upvotes: 2
Views: 448
Reputation: 988
You can set storyboard from code.
<TextBlock Grid.Row="0" x:Name="savetxt" Visibility="Hidden" Text="Hello"></TextBlock>
<Button Grid.Row="1" Content="Test" Height="25" Width="75" Click="Button_Click"></Button>
private void Button_Click(object sender, RoutedEventArgs e)
{
savetxt.Visibility = Visibility.Visible;
Storyboard storyboard = new Storyboard();
TimeSpan duration = new TimeSpan(0, 0, 5);
DoubleAnimation animation = new DoubleAnimation();
animation.From = 1.0;
animation.To = 0.0;
animation.Duration = new Duration(duration);
Storyboard.SetTargetName(animation, savetxt.Name);
Storyboard.SetTargetProperty(animation, new PropertyPath(OpacityProperty));
// Add the animation to the storyboard
storyboard.Children.Add(animation);
// Begin the storyboard
storyboard.Begin(this);
MessageBox.Show(savetxt.Visibility.ToString());
}
Upvotes: 2