如何将WPF触发器绑定到子元素

问题描述 投票:0回答:1

我想重新定义菜单项的模板。

我想要图标前景

PrimarySolidColorBrush
和标题前景
Black
(默认),但是。当鼠标悬停时,图标和标题具有背景
PrimarySolidColorBrush
和前景
White

目前只有标题发生变化,但对图标没有影响。我还尝试在

DataTrigger
(绑定到父级)内使用
ControlTemplate
并使用
TargetName

以下是最少的代码行:

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type MenuItem}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <ContentPresenter Grid.Column="0" ContentSource="Icon" TextBlock.Foreground="{StaticResource PrimarySolidColorBrush}" />
                    <ContentPresenter Grid.Column="1" ContentSource="Header" />
                </Grid>
            </ControlTemplate>
        <Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="TextBlock.Foreground" Value="White" /> <!-- Has no effect on the Icon textbox foreground -->
            <Setter Property="Background" Value="{StaticResource PrimarySolidColorBrush}" />
        </Trigger>
    </Style.Triggers>
</Style>
wpf triggers binding
1个回答
0
投票

TextBlock.Foreground="{StaticResource PrimarySolidColorBrush}"
中删除本地值分配
ContentPresenter
并通过样式设置器设置默认值。
TextBlock.Foreground
属性以及
Control.Foreground
属性自动被子元素树继承(依赖属性继承)。
这意味着在父级
Control.Foreground
上设置
MenuItem
将逐渐渗透到
ContentPresenter

如果通过样式设置器设置该值,则触发器可以覆盖该值,因为触发器优先于样式设置器。
但是,如果该值是在本地设置的(就像您当前为

ContenPresenter
所做的那样),则本地值占主导地位,因为它优先于每个非本地值,动画和依赖属性强制除外(请参阅 Microsoft 学习:依赖属性优先级列表)。

  <!-- Set the default. Will be dynamically replaced by the trigger and restored after the trigger became invalid. -->
  <Setter Property="Foreground"
          Value="{StaticResource PrimarySolidColorBrush}" />

  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type MenuItem}">
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
          </Grid.ColumnDefinitions>
          
          <ContentPresenter Grid.Column="0" 
                            ContentSource="Icon" />
          <ContentPresenter Grid.Column="1" 
                            ContentSource="Header" />
        </Grid>
      </ControlTemplate>
    <Setter.Value>
  </Setter>

  <Style.Triggers>
    <Trigger Property="IsMouseOver" 
             Value="True">
      <Setter Property="Foreground" 
              Value="White" /> <!-- Now successfully overrides the default set by the style setter -->
      <Setter Property="Background" 
              Value="{StaticResource PrimarySolidColorBrush}" />
    </Trigger>
  </Style.Triggers>
</Style>
© www.soinside.com 2019 - 2024. All rights reserved.