简体   繁体   中英

Is there a way to assign a dynamic resource to a dependency property in code

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM