gpt4 book ai didi

c# - WPF 在 X 秒后淡出状态栏文本?

转载 作者:IT王子 更新时间:2023-10-29 04:41:23 25 4
gpt4 key购买 nike

我正在尝试想出一种不显眼的方式来向用户显示小错误消息。所以我在我的表单中添加了一个状态栏,

    <StatusBar Margin="0,288,0,0" Name="statusBar" Height="23" VerticalAlignment="Bottom">
<TextBlock Name="statusText">Ready.</TextBlock>
</StatusBar>

然后当他们点击“添加”按钮时,它应该做一些事情,或者显示一条错误消息:

private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
addressBar.Focus();
var url = addressBar.Text.Trim();
if (string.IsNullOrEmpty(url))
{
statusText.Text = "Nothing to add.";
return;
}
if (!url.Contains('.'))
{
statusText.Text = "Invalid URL format.";
return;
}
if (!Regex.IsMatch(url, @"^\w://")) url = "http://" + url;
addressBar.Text = "";

但该消息在应用程序的整个生命周期内一直存在...我想我应该在大约 5 秒后重置它...我如何设置计时器来执行此操作?

奖励:我如何在这样做时给它一个漂亮的淡出效果?


我创建了一个System.Timers.Timer

    private Timer _resetStatusTimer = new Timer(5000);

void _resetStatusTimer_Elapsed(object sender, ElapsedEventArgs e)
{
statusText.Text = "Ready";
}

但是 Elapsed 事件运行在与 UI 不同的线程上,它不喜欢这样……我该如何解决这个问题?

最佳答案

您可以使用 Storyboard 来实现这个目的。

<Storyboard x:Key="Storyboard1">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="statusBarItem">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="1"/>
<EasingDoubleKeyFrame KeyTime="0:0:3" Value="1"/>
<EasingDoubleKeyFrame KeyTime="0:0:4" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>

当必须显示消息时,您只需以编程方式调用 StoryBoard 的 Begin 方法或插入一个触发器,如下所示。

<Window.Triggers>
<EventTrigger RoutedEvent="TextBoxBase.TextChanged" SourceName="textBox">
<BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
</EventTrigger>
</Window.Triggers>

编辑:另一种选择是这样做:

<TextBlock Name="statusText" Text="{Binding Path=StatusBarText, NotifyOnTargetUpdated=True}">
<TextBlock.Triggers>
<EventTrigger RoutedEvent="Binding.TargetUpdated">
<BeginStoryboard>
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.25" Value="1"/>
<EasingDoubleKeyFrame KeyTime="0:0:4" Value="1"/>
<EasingDoubleKeyFrame KeyTime="0:0:5" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</TextBlock.Triggers>

然后在这种情况下创建一个名为 StatusBarText 的 DependencyProperty,实现如下:

public string StatusBarText
{
get { return (string)GetValue(StatusBarTextProperty); }
set { SetValue(StatusBarTextProperty, value); }
}

// Using a DependencyProperty as the backing store for StatusBarText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StatusBarTextProperty =
DependencyProperty.Register("StatusBarText", typeof(string), typeof(MyOwnerClass), new UIPropertyMetadata(""));

希望这对您有所帮助。

关于c# - WPF 在 X 秒后淡出状态栏文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3970986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com