我在资源字典中定义了一个ComponentResourceKey,如下所示:
<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="4,4,0,0" />
</Style>我有一个静态类,用作提供资源键的快捷方式,如下所示:
public class Resources
{
public static ComponentResourceKey BaseControlStyleKey
{
get
{
return new ComponentResourceKey(typeof(Resources), "BaseControlStyle");
}
}
}通常,当我使用这种风格时,我会这样做:
<TextBlock Style="{DynamicResource {x:Static local:Resources.BaseControlStyleKey}}"/>但是,我有一个需要在代码中设置样式的场景,如下所示:
myTextBox.Style = Resources.BaseControlStyleKey // Does not work.你知道如何从ComponentResourceKey中提取样式吗?
发布于 2008-12-03 16:46:27
我想通了。
myTextBox.Style =
Application.Current.TryFindResource(Resources.BaseControlStyleKey)
as Style;发布于 2009-03-26 14:55:06
在创建了一个单独的ComponentResourceKey持有者(资源类)之后,您可以简化键声明。
用代替:
<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="4,4,0,0" />
</Style>您可以简单地使用::
<Style x:Key="{x:Static local:Resources.BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="4,4,0,0" />
</Style>https://stackoverflow.com/questions/337803
复制相似问题