简体   繁体   中英

Static Variable bound to textblock not updated

I'm using a textblock with a binding to a variable in a static class. If the variable is set initially within the class, the text is updated. But when the variable changes within a method the bound textblock text does not change.

I set the value initialy to "initial text" and afterwards, I try to change it within a method. But the text never changes, even if i see it changes in the debugger.

I added a textblock with a binding to a static variable:

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

In the code, I implemented the following class:

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;

}

What I expected was, that the text updates every time I call the method showMessage. But the text keeps the value "initial text"

Does anyone has an idea what I'm doing wrong? Best regrads hafisch

Besides that you must update the property - not its backing field - by calling

InfoBannerText = "changed text";

you have to use a Binding for the Text property, instead of just an assignment:

Text="{Binding Path=(local:InfoBanner.InfoBannerText)}"

Thanks for your comments:

I adjusted all your suggestions. But still it's not updated:

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;

}

Thanks for your answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM