I am writing Style Setters for custom WPF controls and would like to set values to resources (such as Brushes) that would ideally (read "hopefully") be defined at an application-level (so that app-wide theming is enabled). One example would look something like this:
<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>
Now to make the Style usable in the case that the resource has not yet been defined at the application-level, I would like to be able to define the brush locally in Xaml and have that definition be used if a resource with that same key is not found elsewhere. Conceptually speaking, it would be analogous to using an "if not defined" preprocessor directive such as #ifndef
.
Perhaps there already exists a mechanism for doing this. If not, how could it be implemented? Could an attached property/behavior somehow do this? If so, I envision its usage looking something like this:
<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>
I realize that one workaround might be to leave the generic custom control Style pretty bland, then write inherited Styles that for each application that use references to resources that exist in that application. But I'm hoping there is a more elegant approach that generalizes across applications better.