How do I get the actual resource from a ComponentResourceKey?

吃可爱长大的小学妹 提交于 2019-12-22 11:17:35

问题


I have a ComponentResourceKey defined in my resource dictionary like this:

<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
    <Setter Property="Margin" Value="4,4,0,0" />
</Style>

I have a static class that I use as a shortcut to provide the resource keys liek this:

public class Resources
{
    public static ComponentResourceKey BaseControlStyleKey
    {
        get
        {
            return new ComponentResourceKey(typeof(Resources), "BaseControlStyle");
        }
    }
}

Now typically when I use this style I do something like this:

<TextBlock Style="{DynamicResource {x:Static local:Resources.BaseControlStyleKey}}"/>

However, I have a scenario where I need to set a style in code like this:

myTextBox.Style = Resources.BaseControlStyleKey // Does not work.

Any ideas how I extract the style from the ComponentResourceKey?


回答1:


I figured it out.

myTextBox.Style = 
        Application.Current.TryFindResource(Resources.BaseControlStyleKey)
        as Style;



回答2:


After you have created a separate ComponentResourceKey holder (Resources class) you can simplify your key declaration.

Instead of:

<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Resources}, ResourceId=BaseControlStyle}" TargetType="{x:Type FrameworkElement}">
    <Setter Property="Margin" Value="4,4,0,0" />
</Style>

You can simply use:

<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/how-do-i-get-the-actual-resource-from-a-componentresourcekey

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