首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从ComponentResourceKey获取实际资源?

如何从ComponentResourceKey获取实际资源?
EN

Stack Overflow用户
提问于 2008-12-03 16:39:05
回答 2查看 6.7K关注 0票数 3

我在资源字典中定义了一个ComponentResourceKey,如下所示:

代码语言:javascript
复制
<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
    <Setter Property="Margin" Value="4,4,0,0" />
</Style>

我有一个静态类,用作提供资源键的快捷方式,如下所示:

代码语言:javascript
复制
public class Resources
{
    public static ComponentResourceKey BaseControlStyleKey
    {
        get
        {
            return new ComponentResourceKey(typeof(Resources), "BaseControlStyle");
        }
    }
}

通常,当我使用这种风格时,我会这样做:

代码语言:javascript
复制
<TextBlock Style="{DynamicResource {x:Static local:Resources.BaseControlStyleKey}}"/>

但是,我有一个需要在代码中设置样式的场景,如下所示:

代码语言:javascript
复制
myTextBox.Style = Resources.BaseControlStyleKey // Does not work.

你知道如何从ComponentResourceKey中提取样式吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2008-12-03 16:46:27

我想通了。

代码语言:javascript
复制
myTextBox.Style = 
        Application.Current.TryFindResource(Resources.BaseControlStyleKey)
        as Style;
票数 4
EN

Stack Overflow用户

发布于 2009-03-26 14:55:06

在创建了一个单独的ComponentResourceKey持有者(资源类)之后,您可以简化键声明。

代替:

代码语言:javascript
复制
<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
    <Setter Property="Margin" Value="4,4,0,0" />
</Style>

您可以简单地使用::

代码语言:javascript
复制
<Style x:Key="{x:Static local:Resources.BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
    <Setter Property="Margin" Value="4,4,0,0" />
</Style>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/337803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档