更新TextBlock.Text On Opacity = 0.0

时间:2014-12-14 15:15:35

标签: c# wpf

我想在Opacity值为0.0时更改TextBlock.Text。 TextBlock通过故事板上的DoubleAnimation进行动画处理(不透明度从3秒逐渐淡入1.0到0.0,重复和自动反转)。这甚至可以使用DoubleAnimation或Storyboard Events吗?我尝试在CurrentStateInvalidated和CurrentTimeInvalidated中更改TextBlock的Text属性,但这些只触发一次。

编辑:这是我到目前为止的触发器。这不会产生预期的结果。

public MainWindow()
    {
        InitializeComponent();
        this.Loaded += delegate
        {
            Style st = new Style();
            st.TargetType = typeof(TextBlock);
            DataTrigger t = new DataTrigger();
            t.Value = (double)0.0;
            t.Binding = new Binding()
            {
                Path = new PropertyPath("Opacity"),
                RelativeSource = RelativeSource.Self
            };
            Setter se = new Setter();
            se.Property = TextBlock.TextProperty;
            se.Value = GetTickerString();
            t.Setters.Add(se);
            st.Triggers.Clear();
            st.Triggers.Add(t);
            txblkTickerText1.Style = st;
        };
    }

3 个答案:

答案 0 :(得分:1)

如果不透明度等于0,则不会显示任何文字。我做了一个简单的例子,但是一旦不透明度等于0.7

就会调用文本更改
<Window.Triggers>
    <EventTrigger RoutedEvent="Loaded">
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation Storyboard.TargetName="TextBlockElement" Storyboard.TargetProperty="Opacity" To="0.7"/>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>
<StackPanel>
    <TextBlock Name="TextBlockElement">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Setter Property="Text" Value="text"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Opacity}" Value="0.7">
                        <Setter Property="Text" Value="Opacity is 0.7"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</StackPanel>

答案 1 :(得分:0)

在代码中启动StoryBoard,然后立即启动DispatcherTimer,以获得不透明度变为零所需的时间。因此,在tick DispatcherTimer事件中,您可以设置文字。

说,

void func()
{
    StoryBoard myStoryBoard;
    //configure it
    myStoryBoard.Begin();
    DispatcherTimer _timer = new DispatcherTimer();
    _timer.Interval = new TimeSpan(0,0,1);
    _timer.Tick += _timer_Tick;
    _timer.Start();
}

void _timer_Tick(object sender, EventArgs e)
{
    yourTextBlock.Text = "changedText";
    (sender as DispatcherTimer).Stop();
}

答案 2 :(得分:0)

您可以简单地处理不透明度动画的Completed事件:

DoubleAnimation animation = ...

animation.Completed +=
    (o, e) =>
    {
        textBlock.Text = "Opacity animation completed.";
    };