Todd J. York
Todd J. York

Reputation: 145

Binding a static resource to an existing value in WPF

I want to simplify bindings in WPF. Say, I'm creating a FontFamily resource in App.xaml which binds to a string value in the application settings, to avoid a long line of binding expression in every window. But I found that I couldn't find a way to do that.

It is said that there's a x:Arguments in XAML 2009, but that does not apply here.

My approaches:

<DynamicResource x:Key="PrimaryFont" ResourceKey="{Binding PrimaryFont, Source={x:Static properties:Settings.Default}, Converter={StaticResource StringToFontFamilyConverter}}"/>

failed, throwing an XamlParseException.

<FontFamily x:Key="PrimaryFont">
    <Binding Path="PrimaryFont" Source="{x:Static properties:Settings.Default}" Converter="{StaticResource StringToFontFamilyConverter}"/>
</FontFamily>

this even does not compile.

I don't want to add that in code behind, because I don't want to make everything look like a mess. Is that possible?

EDIT: this is not a duplicate of Setting global font family. The FontFamily is just for explaining purpose, in real world there will be more than one kind of element I want to simplify the binding on, and the element might not be a good target for a new style.

Upvotes: 1

Views: 2006

Answers (1)

Todd J. York
Todd J. York

Reputation: 145

Turns out I found an interesting solution in the process of dealing with another problem.

This awesome little proxy class mentioned in this article written by @ThomasLevesque is my life saver:

public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

And thanks to @mkoertgen for sharing that find in this answer.

Upvotes: 1

Related Questions