1

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.

Community
  • 1
  • 1
Todd J. York
  • 135
  • 2
  • 12
  • 1
    I don't see how this is a duplicate of that? – KyloRen Mar 04 '17 at 11:48
  • There is no need for a converter and therefore, the Binding part is relatively small: ``FontFamily="{Binding MyFont, Source={x:Static p:Settings.Default}}"``, assuming that there is ``string`` named ``MyFont`` in ``Settings.Default``. Also, I used ``p`` instead of ``properties`` to make it smaller. – rmojab63 Mar 04 '17 at 11:50
  • @Ron thanks. I'll use that on the appliable settings for now. – Todd J. York Mar 04 '17 at 11:56

1 Answers1

1

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.

Community
  • 1
  • 1
Todd J. York
  • 135
  • 2
  • 12