Data binding with static properties in WPF

2019-07-21 07:58发布

问题:

I have a simple static property FontSizeTitle which is supposed to be used for the stylised title in all instances of HandledWindow type, and update from the same static property at the same time without explicit notification after changing the property. by the settings panel or whatever that will change the property in order to change and update font sizes for all titles for all windows visually.

Here is the code of my stylised title in XAML, which is part of a template for the HandledWindow, which is part of a standard XAML style page, which is loaded by a resource dictionary from another library at startup. so it applies for all HandledWindow instances that will appear in the application:

<TextBlock x:Name="TitleText"
       TextWrapping="Wrap"
       Text="Window Title"
       FontSize="{Binding Source={x:Static UI:HandledWindow.FontSizeTitle}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
       VerticalAlignment="Stretch"
       FontFamily="{DynamicResource FontFamiliy}" />

Here is my simple static property, Note that binding actually works for the first time only.

public static double FontSizeTitle
{
    get;
    set;
}

By the base constructor of HandledWindow type it is set to 15, That size is working, But if setting it once again to another size after the initialisation the visual title won't update.

回答1:

Not sure, what version of WPF you are using. WPF 4.5 now supports Binding and Property Change notifications for Static Properties.

Refer to this Blog post for full discussion.

So, your HandledWindows class will become something like:

public static class HandledWindow
{
    private static double _fontSizeTitle;

    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;

    static HandledWindow()
    {
        FontSizeTitle = 15;
    }

    public static double FontSizeTitle
    {
        get { return _fontSizeTitle; }
        set
        {
            _fontSizeTitle = value;
            if (StaticPropertyChanged != null)
                StaticPropertyChanged(null, new PropertyChangedEventArgs("FontSizeTitle"));
        }
    }
}

And the Binding in XAML will become:

FontSize="{Binding Path=(local:HandledWindow.FontSizeTitle), Mode=OneWay}"