質問

あなたは、たとえば、のMenuItemとのContextMenuをネストされた素子構造を持っていると仮定します:

<ContextMenu Style="{StaticResource FooMenuStyle}">
    <MenuItem Style="{StaticResource FooMenuItemStyle}"/>
    ...
</ContextMenu>

あなたは簡単のContextMenuまたはMenuItemの要素にスタイルやテンプレートを適用することができます。 MenuItemのスタイルはメニューのスタイルに属している場合しかし、すべてのMenuItem要素に追加するのは非常に面倒で冗長である。

の子要素に自動的にそれらを適用する方法はありますか?あなたは、単にこれを書くことができるようにます:

<ContextMenu Style="{StaticResource FooMenuStyle}">
    <MenuItem/>
    ...
</ContextMenu>

FooMenuStyleは、MenuItemの要素を含むスタイルができればそれはきちんとしただろうが、それは可能ではないようです。

編集:私はItemContainerStyleを知らなかったとの意図は、一般的な解決策のためだったので、メニューの一例は、おそらく誤解を招くおそれがあります。 1一般的な変種とItemContainerStyleのための1など:

私は2つの解決策が出ている2つの答えに基づいて、
<Style x:Key="FooMenuItem" TargetType="{x:Type MenuItem}">
    ...
</Style>

<Style x:Key="FooMenu" TargetType="{x:Type ContextMenu}">
    <!-- Variant for specific style attribute -->
    <Setter Property="ItemContainerStyle"
            Value="{StaticResource FooMenuItem}"/>

    <!-- General variant -->
    <Style.Resources>
        <Style TargetType="{x:Type MenuItem}"
               BasedOn="{StaticResource FooMenuItem}"/>
    </Style.Resources>
</Style>

<ContextMenu Style="{StaticResource FooMenu}">
    <MenuItem/>
</ContextMenu>
役に立ちましたか?

解決

<ContextMenu>
   <ContextMenu.Resources>
      <Style TargetType="{x:Type MenuItem}">
         <!--Setters-->
      </Style>
   </ContextMenu.Resources>
   <MenuItem/>
   <!--Other MenuItems-->
</ContextMenu>

スタイルがされたContextMenu内のすべてのMenuItemオブジェクトに適用されます。

他のヒント

ただ、元の答えを完了するために、私はそれがそのような親の内側にネストされたスタイルを追加する明確だと思います:

<Style x:Key="WindowHeader" TargetType="DockPanel" >
    <Setter Property="Background" Value="AntiqueWhite"></Setter>
    <Style.Resources>
        <Style TargetType="Image">
            <Setter Property="Margin" Value="6"></Setter>
            <Setter Property="Width" Value="36"></Setter>
            <Setter Property="Height" Value="36"></Setter>
        </Style>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap"></Setter>
        </Style>
    </Style.Resources>
</Style>
<ContextMenu ItemContainerStyle="{StaticResource FooMenuItemStyle}">
    <MenuItem/>
</ContextMenu>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top