在 WPF 中设置嵌套元素的样式 [英] Styling nested elements in WPF

查看:23
本文介绍了在 WPF 中设置嵌套元素的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个嵌套的元素结构,例如带有 MenuItems 的 ContextMenu:

Suppose you have a nested element structure, for example a ContextMenu with MenuItems:

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

您可以轻松地将样式或模板应用于 ContextMenu 或 MenuItem 元素.但是如果 MenuItem 样式属于 Menu 样式,那么将它添加到每个 MenuItem 元素中是相当麻烦和多余的.

You can easily apply styles or templates to the ContextMenu or MenuItem elements. But if the MenuItem style belongs to the Menu style it is quite cumbersome and redundant to add it to every MenuItem element.

有什么办法可以自动将这些应用到子元素上?这样你就可以简单地写这个:

Is there any way to apply those automatically to child elements? So that you can simply write this:

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

如果 FooMenuStyle 可以设置包含 MenuItem 元素的样式就好了,但这似乎不可能.

It would be neat if FooMenuStyle could style containing MenuItem elements, but that does not seem to be possible.

菜单示例可能具有误导性,因为我不知道 ItemContainerStyle 并且意图是通用解决方案.基于这两个答案,我提出了两种解决方案:一种是通用变体,另一种是针对 ItemContainerStyle 之类的:

The Menu example is probably misleading since I was unaware of ItemContainerStyle and the intent was for a general solution. Based on the two answers I have come up with two solutions: one general variant and one for ItemContainerStyle and the like:

<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 对象.

The style will be applied to all MenuItem objects within the ContextMenu.

这篇关于在 WPF 中设置嵌套元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆