Home > Back-end >  Is there a way to assign a dynamic resource to a dependency property in code
Is there a way to assign a dynamic resource to a dependency property in code

Time:06-03

I have a SolidColorBrush defined in a Resource Dictionary as follows:

 <Color x:Key="ColorGray100">#F5F6F7</Color>

 <SolidColorBrush x:Key="BrushGray100" Color="{DynamicResource ColorGray100}" />

I have a Dependency Property defined in the code behind for a user control as follows:

    /// <summary>
    /// get/set the brush for the pattern ring.
    /// The pattern ring is a full circle which the progress ring is drawn over.
    /// This Brush value is defaulted to Brushes.LightGray
    /// </summary>
    public Brush PatternRingBrush
    {
        get => (Brush)GetValue(PatternRingBrushProperty);
        set => SetValue(PatternRingBrushProperty, value);
    }

    public static readonly DependencyProperty PatternRingBrushProperty =
        DependencyProperty.Register("PatternRingBrush", typeof(Brush), typeof(UXProgressRing),
            new UIPropertyMetadata(Brushes.LightGray));

How can I assign the "BrushGray100" SolidColorBrush as the default UIPropertyMetadata value instead of Brushes.LightGray?

CodePudding user response:

It is not possible to assign a dynamic resource to dependency property's default value. (Nor would it make sense because the default value is evaluated once, whereas a dynamic resource can by definition change)

However, if your goal is to assign the actual dependency property value to a dynamic resource, effectively binding the property to the dynamic resource, there already exist answers on this site that describe how to do that. This appears to be the best existing solution.

I'm posting this as an answer instead of marking as duplicate because your question specifically asks about setting the default value.

  • Related