【问题标题】:Alerting User By Changing Background of Control C#通过更改控件 C# 的背景来提醒用户
【发布时间】:2017-07-13 14:45:47
【问题描述】:

我正在使用 WPF(C#) 进行编程。我想提醒用户填写空文本框(或任何其他控件)。我想闪光控制以提醒他/她。这是我使用它们的代码,但它不会改变颜色:

static void AlertByChangingBackground(Control control)
{
    Action a = () =>
    {
        control.Background = System.Windows.Media.Brushes.Red;
        Thread.Sleep(500);
        control.Background = System.Windows.Media.Brushes.White;
    };

    control.Dispatcher.Invoke(a);
} 

可以看出,我也使用Action,但它不起作用。我也在Sleep 方法之前使用control.UpdateLayout(),但它也不起作用。我该如何解决这个问题。

更新 1:

现在,我使用如下所示的代码。但问题是当函数被多次调用时(特别是在短时间内连续调用时),文本的颜色不会回到它的第一个颜色。例如,我的控制可能保持在红色。我该如何解决?

public static void AlertByChangingBackground(Control control)
{
    Action a = () =>
    {
        ColorAnimation animation;
        animation = new ColorAnimation();

        animation.From = Colors.Red;
        animation.To = ToColor(control.Background);
        animation.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 330));

        RepeatBehavior rb = new RepeatBehavior(3);
        animation.RepeatBehavior = rb;
        control.Background = new SolidColorBrush(Colors.Red);
        control.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);
    };

    control.Dispatcher.BeginInvoke(a);
}

我注意到我想从控件的当前背景开始动画,而不是从白色或任何预定义的颜色。

【问题讨论】:

  • 您应该查看animations 而不是试图冻结线程的执行。
  • 我不知道这对于您的应用程序是否过分,但对于用户输入验证,我强烈推荐 FluentValidation 库:github.com/JeremySkinner/FluentValidation
  • @3615 谢谢,为什么不复制您的文字作为答案?我想接受你的方法作为我的回答。
  • 对不起,我没有时间给你一个完整的答案,这就是我简单评论的原因。我很高兴它对你有所帮助:)

标签: c# wpf controls background-color


【解决方案1】:

您可以使用触发器或动画来提醒用户,而不是使用线程,

您可以添加 xmlns:sys="clr-namespace:System;assembly=mscorlib" 命名空间来检查字符串是否为空。

<Style TargetType="{x:Type TextBox}" x:Key="AlertStyle">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Text,RelativeSource={RelativeSource Mode=Self}}" Value="{x:Static sys:String.Empty}">
                <Setter Property="Background" Value="Red"></Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>

为您的 TextBox 控件使用这种样式,如下所示,

  <TextBox Width="100" Height="25" Style="{StaticResource AlertStyle}">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多