Return a dynamic resource from a converter

喜欢而已 提交于 2019-12-05 07:06:33

You cannot return something dynamic from a converter, but if your only condition is a bool you can easily replace the whole converter with a Style using Triggers:

e.g.

<Style TargetType="TextBox">
    <Setter Property="Background" Value="Transparent" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsChecked, ElementName=WarnStatusSource}" Value="True">
            <Setter Property="Background" Value="{DynamicResource WarningColor}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

If now the resource with that key is changed the background should change as well.

The way to return a dynamic resource reference is pretty simple using a DynamicResourceExtension constructor and supplying it a resource key.

Usage:

return new DynamicResourceExtension(Provider.ForegroundBrush);

Definition of the Provider class should contains the key:

public static ResourceKey ForegroundBrush 
{ 
    get 
    { 
        return new ComponentResourceKey(typeof(Provider), "ForegroundBrush"); 
    } 
}

And the value for the key would be declared in the resource dictionary:

<ResourceDictionary
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:theme="clr-namespace:Settings.Appearance;assembly=AppearanceSettingsProvider">

<Color x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type theme:Provider}, ResourceId=ForegroundColor}">#FF0000FF</Color>

<SolidColorBrush x:Key="{ComponentResourceKey {x:Type theme:Provider}, ForegroundBrush}" Color="{DynamicResource {ComponentResourceKey {x:Type theme:Provider}, ForegroundColor}}" />
</ResourceDictionary>

This way, the converter would dynamically assign a DynamicResource to the bound property depending on the resource key supplied.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!