[英]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:我在资源字典中定义了一个 SolidColorBrush,如下所示:
<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?如何将“BrushGray100”SolidColorBrush 指定为默认 UIPropertyMetadata 值而不是 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.我将其发布为答案而不是标记为重复,因为您的问题专门询问设置默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.