Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: is there an event triggered on resource change

is there a way to get notified on value changes of a specific WPF resource?

We need to dynamically adapt the content font size in a WPF application... For WPF controls, we set Control.FontSize to a dynamic resource and the font resizes automatically. Unfortunately, we also have an embedded winforms control, which font size cannot be set that way. The idea was to subscribe to an event triggered on each resource value-change and to implement a custom refresh of the winforms control. Any suggestion?

Thank you in advance!

like image 420
jeromerg Avatar asked Apr 03 '14 15:04

jeromerg


1 Answers

So,

after considering all possible ways, I introduced a new behavior that triggers an event on each change of a specific WPF resource.

The source can be downloaded or cloned from https://github.com/jeromerg/ResourceChangeEvent.

public class ResourceChangeNotifierBehavior 
  : System.Windows.Interactivity.Behavior<FrameworkElement>
{
    public static readonly DependencyProperty ResourceProperty 
            = DependencyProperty.Register("Resource", 
                   typeof(object),
                   typeof(ResourceChangeNotifierBehavior),
                   new PropertyMetadata(default(object), ResourceChangedCallback));

    public event EventHandler ResourceChanged;

    public object Resource
    {
        get { return GetValue(ResourceProperty); }
        set { SetValue(ResourceProperty, value); }
    }

    private static void ResourceChangedCallback(DependencyObject dependencyObject,
                                                DependencyPropertyChangedEventArgs args)
    {
        var resourceChangeNotifier = dependencyObject as ResourceChangeNotifierBehavior;
        if (resourceChangeNotifier == null)
            return;

        resourceChangeNotifier.OnResourceChanged();
    }

    private void OnResourceChanged()
    {
        EventHandler handler = ResourceChanged;
        if (handler != null) handler(this, EventArgs.Empty);
    }
}

So that an event-handler OnResourceChanged can be hooked in the XAML file as following:

<i:Interaction.Behaviors>
    <Behaviours:ResourceChangeNotifierBehavior 
                Resource="{DynamicResource MyDynamicResourceKey}"
                ResourceChanged="OnResourceChanged"/>
</i:Interaction.Behaviors>

Hope, it helps...

like image 150
jeromerg Avatar answered Oct 06 '22 00:10

jeromerg