2008-12-03 125 views
2

我在資源字典中定義這樣的ComponentResourceKey:如何從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> 

我有我的快捷方式使用提供資源鍵liek這是一個靜態類:

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中提取樣式?

回答

3

我想通了。

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

在創建單獨的ComponentResourceKey保持器(Resources類)後,可以簡化您的密鑰聲明。

相反的:

<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>