在 Style.Resources 中使用 StaticResourceExtension 时出错 [英] Error when using StaticResourceExtension inside Style.Resources
问题描述
我在模板中使用 DynamicResource,并在使用该模板的每个样式中使用 StaticResourceExtensions 作为资源,以便在每个样式中对 DynamicResource 进行不同的评估.
I am using DynamicResource in a template, and StaticResourceExtensions as resource inside each style using that template, so that the DynamicResource is evaluated differently in each of them them.
问题是,我收到此错误:
The problem is, I get this error:
Unable to cast object of type 'System.Windows.Media.Effects.DropShadowEffect' to type 'System.Windows.ResourceDictionary'
这是我的代码:
<DropShadowEffect
x:Key="Sombra"
Opacity="0.5"
ShadowDepth="3"
BlurRadius="5"
/>
<ControlTemplate
x:Key="ControleGeometriaTemplate"
TargetType="{x:Type Control}"
>
<Border
x:Name="border"
Background="{TemplateBinding Background}"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
/>
<Path
x:Name="ícone"
Fill="{TemplateBinding Foreground}"
Effect="{DynamicResource PathShadow}"
/>
</Border>
</ControlTemplate>
<Style x:Key="BotãoGeometria" TargetType="{x:Type ButtonBase}">
<Setter Property="Template" Value="{StaticResource ControleGeometriaTemplate}"/>
</Style>
<Style
x:Key="BotãoNavegaçãoBase"
TargetType="{x:Type ButtonBase}"
BasedOn="{StaticResource BotãoGeometria}"
>
<Style.Resources>
<StaticResource x:Key="PathShadow" ResourceKey="Sombra"/>
</Style.Resources>
</Style>
推荐答案
据我所知 StaticResourceExtension 在 某些情况.
感觉你发现了类似的情况:
It smells like you found a similar situation:
<SolidColorBrush x:Key="RedBrush" Color="Red" />
<Style TargetType="TextBox" x:Key="Test">
<Style.Resources>
<StaticResourceExtension x:Key="NewRedBrushKey" ResourceKey="RedBrush" />
</Style.Resources>
</Style>
在 Window
中使用 Test
样式足以重现您的问题.
Using the Test
style in your Window
is enough to reproduce your issue.
所以我的建议是使用你自己的扩展:
So my suggestion is to use your own extension:
public class ResourceFinder : System.Windows.Markup.MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
FrameworkElement frameworkElement;
IDictionary dictionary;
IRootObjectProvider rootObjectProvider = (IRootObjectProvider)
serviceProvider.GetService(typeof(IRootObjectProvider));
if (rootObjectProvider != null)
{
dictionary = rootObjectProvider.RootObject as IDictionary;
if (dictionary != null)
{
return dictionary[ResourceKey];
}
else
{
frameworkElement = rootObjectProvider.RootObject as FrameworkElement;
if (frameworkElement != null)
{
return frameworkElement.TryFindResource(ResourceKey);
}
}
}
return null;
}
public object ResourceKey
{
get;
set;
}
}
那么你的风格就会变成:
Then your style will become:
<Style
x:Key="BotãoNavegaçãoBase"
TargetType="{x:Type ButtonBase}"
BasedOn="{StaticResource BotãoGeometria}">
<Style.Resources>
<local:ResourceFinder x:Key="PathShadow" ResourceKey="Sombra" />
</Style.Resources>
</Style>
我希望这可以帮助您解决问题.
I hope this can help you with your issue.
这篇关于在 Style.Resources 中使用 StaticResourceExtension 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!