绑定到文本块的静态变量未更新

问题描述 投票:0回答:2

我正在使用文本块,该文本块具有对静态类中的变量的绑定。如果在类中最初设置了变量,则将更新文本。但是,当变量在方法中更改时,绑定的文本块文本不会更改。

我将初始值设置为“初始文本”,然后尝试在一个方法中更改它。但是文本永远不会改变,即使我在调试器中看到它也改变了。

我添加了一个带有绑定到静态变量的文本块:

<TextBlock Text="{x:Static local:InfoBanner.InfoBannerText}"/>

在代码中,我实现了以下类:

public static class InfoBanner
{
    static InfoBanner()
    {
        infoBannerText = "initial text";
    }

    public static void showMessage(Window window)
    {
        infoBannerText = "changed text";
        Storyboard sb = window.FindResource("storyInfoBanner") as Storyboard;
        sb.Begin();
    }

    public static string infoBannerText;

    public static String InfoBannerText
    {
        get { return infoBannerText; }
        set {
            infoBannerText = value;
            StaticPropertyChanged?.Invoke(null, FilterStringPropertyEventArgs);
        }
    }

    public static readonly PropertyChangedEventArgs FilterStringPropertyEventArgs = new PropertyChangedEventArgs(nameof(InfoBannerText));
        public static event PropertyChangedEventHandler StaticPropertyChanged;

}

我期望的是,每次我调用showMessage方法时,文本都会更新。但是文本保留值“初始文本”

有人知道我在做什么错吗?最佳成绩hafisch

c# wpf binding static textblock
2个回答
0
投票

感谢您的评论:

我调整了您的所有建议。但仍然没有更新:

public static class InfoBanner
{
    static InfoBanner()
    {
        InfoBannerText = "Initial Text";
    }

    public static void showMessage(Window window)
    {
        InfoBannerText = "Changed text";
        Storyboard sb = window.FindResource("storyInfoBanner") as Storyboard;
        sb.Begin();

    }

    public static string infoBannerText;

    public static String InfoBannerText
    {
        get { return infoBannerText; }
        set {
            infoBannerText = value;
            StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(nameof(InfoBannerText)));
        }
    }

    public static event PropertyChangedEventHandler StaticPropertyChanged;

}

感谢您的回答。


0
投票

此外,您必须通过调用来更新属性-而不是其后备字段->

InfoBannerText = "changed text";

您必须为文本属性使用Binding,而不仅仅是分配:

Text="{Binding Path=(local:InfoBanner.InfoBannerText)}"
© www.soinside.com 2019 - 2024. All rights reserved.