【问题标题】:Prevent ItemContainerStyle from overriding already set Style防止 ItemContainerStyle 覆盖已设置的 Style
【发布时间】:2023-03-04 09:33:02
【问题描述】:

有没有办法防止 ItemContainerStyle 覆盖已经设置的样式(例如通过<Style TargetType="{x:Type MenuItem}">)?

MenuItem 的样式已在 ResourceDictionary XAML 文件中定义,该文件在应用启动时加载:

<ResourceDictionary>
  <Style TargetType="{x:Type MenuItem}">
    <Setter Property="Foreground" Value="{DynamicResource TextForeground}"/>
    .. and so on
  </Style>
</ResourceDictionary>

我有以下MenuItem XAML 定义。 MenuItem 被包裹在通用 TextBlockContextMenu 中(我猜值得一提)。菜单本身一切顺利,但其子项(Enum 的实际值)获得了不同的样式,因为 ItemContainerStyle 覆盖了它:

<MenuItem Header="DisplayType" 
          Name="DisplayTypeMenu"
          ItemsSource="{Binding Source={StaticResource DisplayTypeValues}}">

  <MenuItem.ItemContainerStyle>
    <Style TargetType="MenuItem">
      <Setter Property="MenuItem.IsCheckable" Value="True" />

      <Style.Triggers>
        <Trigger Property="MenuItem.Header" 
                 Value="{x:Static enums:DisplayType.Description}" >
            <Setter Property="MenuItem.IsChecked" Value="True" />
        </Trigger>
      </Style.Triggers>

    </Style>
  </MenuItem.ItemContainerStyle>

</MenuItem>

ItemContainerStyle 源自another question of mine

MenuItem 放置在其他层中,顶层是自定义 ContentControl:

public class SomeGradientPanel : ContentControl
{
    public SomeGradientPanel ()
    {
        DefaultStyleKey = typeof(SomeGradientPanel );
    }
}

上面的代码似乎是问题根源的一个很好的候选者!?

因此,完整的结构是:

<SomeNameSpace:SomeGradientPanel>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"></RowDefinition>
            <RowDefinition Height="20"></RowDefinition>
        </Grid.RowDefinitions>

        <TextBlock x:Name="SomeLabel">

          <TextBlock.ContextMenu>
              <ContextMenu>
                  <!-- The MenuItem code snippet from above !-->
              </ContextMenu>
          </TextBlock.ContextMenu>

        </TextBlock>

    </Grid>
</SomeNameSpace:SomeGradientPanel>

我可以在ItemContainerStyle 中为MenuItem 引用已经定义的Style 吗?样式覆盖仅发生在上述MenuItem 的子代上,父代具有预期的样式。

感谢您的意见!

【问题讨论】:

    标签: c# wpf xaml wpf-controls


    【解决方案1】:

    你试过了吗

    <MenuItem.ItemContainerStyle> 
        <Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
    

    【讨论】:

    • 是的,但这会使子项以比以前更基本的样式显示(例如,缺少文本/标题)。再次感谢您的意见!
    • @Dr1Ku:当然 :) 我无法重现这一点。您是否包含任何其他可能导致应用隐式 MenuItem 样式的资源?像 PresentationFramework.Aero 或 app.xaml 中的东西?
    • @Dr1Ku:如果您删除 ItemContainerStyle 的样式,它可以正常工作吗?
    • 我的意思是 app.xaml 中的样式没有它就可以很好地应用:)
    • 不行,我在家里过节,过完年还要去上班检查。有一个好的,感谢您的意见!
    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2019-12-03
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多