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

查看:636
本文介绍了在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天全站免登陆