【问题标题】:How to update the Fore.Color of Label when its Text Changed ...by C# Code in WPF如何在其文本更改时更新标签的 Fore.Color ...通过 WPF 中的 C# 代码
【发布时间】:2019-07-31 23:27:36
【问题描述】:

我在 WPF 中有标签的动态内容。当标签的文本发生更改时,如何更改标签的前景色,我有 Winform 的代码,但 WPF 需要它。 设计器端的 Winform 代码

this.lblSolar.Name= "lblSolar";
this.lblSolar.TextChanged + = new System.EventHandler(this.LblSolar_TextChanged);

text_Changed 函数代码

private void LblSolar_TextChanged(object sender, EventArgs e)
{
var solarCurrent= Convert.ToDouble(_sValues[(int)ValueOfRTC.SupplyCurrent]);
if (supplyCurrent < 1)
{
lblSupply.ForeColor= Color.Yellow;
}
else
{
// Assigning other colors.....
}
}

但我在 WPF XAML 中找不到“TextChanged”属性。那么解决方案是什么? 在此先感谢

【问题讨论】:

    标签: c# wpf visual-studio winforms


    【解决方案1】:

    使用文本框代替标签

    vb.net

    Private Sub TextBox1_TextChanged(sender As Object, e As TextChangedEventArgs) Handles TextBox1.TextChanged
        TextBox1.Foreground = Brushes.Yellow
    End Sub
    

    C#

     private void TextBox1_TextChanged(object sender, TextChangedEventArgs e) {
        TextBox1.Foreground = Brushes.Yellow;
    }
    

    【讨论】:

    • 为什么需要标签?
    【解决方案2】:

    在 WPF 中,Label 不仅是呈现文本的控件。 它是一个 ContentPresenter,可以显示除文本之外的各种控件。因此它没有文本更改事件。 一般来说,在使用 WPF 时,不应以与使用 winforms 相同的方式使用事件。你真的应该考虑开始学习 MVVM 模式,因为从长远来看,它会让你的生活变得更轻松(在艰难的开始之后)。

    但是,如果您坚持使用 usng 事件来执行此操作,则需要使用文本框...但是您可以使文本框看起来像这样的标签:

    this.lblSolar.Name= "lblSolar";
    this.lblSolar.TextChanged + = new System.EventHandler(this.LblSolar_TextChanged);
    this.lblSolar.BorderThickness = 0;
    this.lblSolar.Background = System.Drawing.Color.Transparent;
    this.lblSolar.IsReadOnly = True; 
    

    【讨论】:

      【解决方案3】:

      丹尼斯说的是对的。如果您仍想通过 Label 实现此目的,您可以简单地派生您自己的标签控件,该控件提供类似这样的 ContentChanged 事件。

      public class MyLabel : Label
      {
          static MyLabel()
          {
              ContentProperty.OverrideMetadata(typeof(MyLabel),
                  new FrameworkPropertyMetadata(
                      new PropertyChangedCallback(OnContentChanged)));
          }
      
          private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
          {
              MyLabel lbl = d as MyLabel;
              if (lbl.ContentChanged != null)
              {
                  DependencyPropertyChangedEventArgs args = new DependencyPropertyChangedEventArgs( ContentProperty, e.OldValue, e.NewValue);
                  lbl.ContentChanged(lbl, args);
              }
          }
      
          public event DependencyPropertyChangedEventHandler ContentChanged;
      }
      

      你可以像这样在 XAML 中使用它。

      <local:MyLabel Content="Sample" ContentChanged="MyLabel_ContentChanged"/>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-20
        • 1970-01-01
        • 1970-01-01
        • 2020-04-06
        • 1970-01-01
        • 1970-01-01
        • 2014-07-27
        • 1970-01-01
        相关资源
        最近更新 更多