我正在为自定义 WPF 控件编写样式设置器,并希望将值设置为理想情况下(阅读“希望”)在应用程序级别定义的资源(例如画笔)(以便启用应用程序范围的主题)。一个示例如下所示:
<Style.Triggers>
<DataTrigger Binding="{Binding IsInteresting}" Value="True">
<Setter Property="FontWeight" Value="Bold" />
<!-- Use the brush that is (hopefully) defined at the application-level -->
<Setter Property="Foreground" Value="{StaticResource InterestingBrush}" />
</DataTrigger>
</Style.Triggers>
现在,为了在资源尚未在应用程序级别定义的情况下使样式可用,我希望能够在 Xaml 中本地定义画笔,并且如果具有相同键的资源是,则使用该定义在别处找不到。从概念上讲,它类似于使用“如果未定义”预处理器指令,例如#ifndef
.
也许已经存在这样做的机制。如果没有,如何实施?附加属性/行为可以以某种方式做到这一点吗?如果是这样,我设想它的用法看起来像这样:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:HopefulBehaviors="clr-namespace:HopefulBehaviors"
xmlns:My_Controls="clr-namespace:My_Controls"
>
<!-- IDEA:
Attached property being used to "use the brush that is defined elsewhere
if it was found, if not use this locally-defined one" -->
<SolidColorBrush x:Key="InterestingBrush"
HopefulBehaviors:UseExternalIfFound="True" Color="Red" />
<Style TargetType="{x:Type My_Controls:AwesomeControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsInteresting}" Value="True">
<Setter Property="FontWeight" Value="Bold" />
<!-- now this brush would be defined (at least locally
but an external definition is used if it is found) -->
<Setter Property="Foreground" Value="{StaticResource InterestingBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
我意识到一种解决方法可能是让通用自定义控件 Style 相当平淡,然后为每个使用对该应用程序中存在的资源的引用的应用程序编写继承的 Styles。但我希望有一种更优雅的方法可以更好地概括应用程序。