3

次のように、リソース ディクショナリで 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 からスタイルを抽出する方法はありますか?

4

2 に答える 2

4

私はそれを考え出した。

myTextBox.Style = 
        Application.Current.TryFindResource(Resources.BaseControlStyleKey)
        as Style;
于 2008-12-03T16:46:26.853 に答える
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>
于 2009-03-26T14:55:05.937 に答える