【问题标题】:Is there a way to refresh the WPF UI so that all the texts update with a new value有没有办法刷新 WPF UI,以便所有文本都更新为新值
【发布时间】:2021-11-16 11:21:20
【问题描述】:

在我的 WPF 应用程序中,我有一个包含如下静态字符串的类,我从 XAML 中引用了相同的类。我的意图是更新这些静态字符串,并且 UI 文本应该反映更新。

public class StaticStrings
{
    public static string text1= "sample 1";
    public static string text2= "sample 2";
    public static string text3= "sample 3";
}

在 XAML 中,我将它们称为如下:

<Label 
                    Content="{x:Static local:StaticStrings.text1}" 
                    Background="Transparent" 
                    Margin="5,0,18,3"
                    />
<Button x:Name="btn" 
                    Click="btn_MouseUp"
                    ToolTip="{x:Static local:StaticStrings.text2}"
                    />

在运行时,我会更新 StaticStrings 的文本并希望看到它们反映在 UI 中。如何做到这一点?

【问题讨论】:

  • 我建议你多看看数据绑定
  • 数据绑定是否有助于动态更新内容? @SotirisKoukios-Panopoulos
  • DataBinding 的重点在于,如果数据发生变化,它将动态更新 UI。
  • 另外,使用像not a good practice这样的可变全局状态。

标签: c# .net wpf windows


【解决方案1】:
  1. 修改您的 StaticString 类以支持更改通知并公开要绑定的公共属性:

     public class StaticStrings
     {
         private static string text1 = "sample 1";
         public static string Text1
         {
             get { return text1; }
             set { text1 = value; NotifyStaticPropertyChanged(); }
         }
    
         private static string text2 = "sample 2";
         public static string Text2
         {
             get { return text2; }
             set { text2 = value; NotifyStaticPropertyChanged(); }
         }
    
         private static string text3 = "sample 3";
         public static string Text3
         {
             get { return text3; }
             set { text3 = value; NotifyStaticPropertyChanged(); }
         }
    
         public static event PropertyChangedEventHandler StaticPropertyChanged;
    
         private static void NotifyStaticPropertyChanged([CallerMemberName] string propertyName = null)
         {
             StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
         }
     }
    
  2. 绑定到公共属性:

     <Label 
             Content="{Binding Path=(local:StaticStrings.Text1)}" 
             Background="Transparent" 
             Margin="5,0,18,3"
             />
     <Button x:Name="btn" 
             Click="btn_MouseUp"
             ToolTip="{Binding Path=(local:StaticStrings.Text2)}"
             />
    

【讨论】:

  • 问题是字符串可以是任意数字。这似乎真的很烦人。有没有办法为所有道具自动触发 PropertyChanged 事件。
  • Fody 将引发PropertyChanged 事件的代码注入到在构建时实现INotifyPropertyChanged 的类的属性设置器中。不知道它是否适用于静态属性。否则,您将不得不像我在示例中所做的那样自己实现这些。这并不奇怪或不寻常。
猜你喜欢
  • 2023-03-30
  • 2021-02-13
  • 2018-05-26
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
相关资源
最近更新 更多