假设我有一个 DrawingBrush
,它具有硬编码的三种颜色,即边框、前景和背景。
<!-- Resource -->
<DrawingBrush x:Key="EventIcon" Stretch="Uniform">
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="#FF9200CE" Geometry="F1 M 51.2119,61.4688L 43.4193,61.4688L 43.4194,29.318L 27.8341,29.318L 27.834,61.4688L 20.0414,61.4688L 35.6267,77.1353L 51.2119,61.4688 Z "/>
<GeometryDrawing Brush="#FFB400FF" Geometry="F1 M 44.4789,64.2014L 40.2667,64.2667L 40.13,29.318L 27.8341,29.318L 27.834,61.4688L 20.0414,61.4688L 33.8667,75.1467L 44.4789,64.2014 Z "/>
<GeometryDrawing Geometry="F1 M 51.2119,61.4688L 43.4193,61.4688L 43.4194,29.318L 27.8341,29.318L 27.834,61.4688L 20.0414,61.4688L 35.6267,77.1353L 51.2119,61.4688 Z ">
<GeometryDrawing.Pen>
<Pen Thickness="2" StartLineCap="Round" EndLineCap="Round" LineJoin="Round" Brush="#FF3D0033"/>
</GeometryDrawing.Pen>
</GeometryDrawing>
<GeometryDrawing Brush="#FFFFFFFF" Geometry="F1 M 33.7559,53.2538L 32.6202,40.9989L 32.6202,35.3362L 37.3531,35.3362L 37.3531,40.9989L 36.2333,53.2538L 33.7559,53.2538 Z M 32.6202,59.6771L 32.6202,54.9442L 37.3531,54.9442L 37.3531,59.6771L 32.6202,59.6771 Z "/>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
<!-- Usage -->
<Rectangle Width="16" Height="16" Fill="{StaticResource EventIcon}" />
问题
能够从父 矩形
更改这些颜色,但仍然有默认后备的最佳方法是什么?
当我写这个问题时,我想到了两种可能的解决方案......
可能的解决方案#1
使用 RelativeSource
绑定(bind)将每个属性连接到其等效属性,例如{Binding Path=BorderBrush,RelativeSource={RelativeSource AncestorType={x:type Rectangle}}
但是:
Rectangle
作为Shape
没有BorderBrush
属性;- 我无法提供默认值。在绑定(bind)中指定
FallbackValue
不起作用,因为绑定(bind)将解析并采用默认值。 (编辑:当我写这篇文章时,我想我可能会使用NullValue
属性)。
可能的解决方案#2
编写一个附加属性,该属性采用颜色/画笔数组,然后使用转换器将其映射到GeometryDrawing.Brush
。使用 Binding.IsNull
属性提供默认值,因为如果附加属性为 null 或该颜色未重新映射,则如果无法映射,我可以保证返回 null 值。
最佳答案
我会选择 dynamic resource reference ,在应用程序级别 (Application.Resources
) 定义默认值,并通过在某些控件的资源中添加具有相同键的画笔来在本地更改它们。
关于wpf - 如何在 DrawingBrush 中重新映射颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9886869/