在以编程方式设置Foreground后,MouseOver触发器不起作用

时间:2012-07-29 03:20:24

标签: c# wpf xaml triggers controltemplate

我是WPF的新手,但在网上搜索了几天我无法弄清楚我的问题。

在我以编程方式更改Foreground属性后,IsMouseOver触发器无效。请宽容并提前感谢:)

<Style x:Key="ZizaMenuItem" TargetType="{x:Type Button}">
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="Margin" Value="5,0,5,0"/>
    <Setter Property="Height" Value="30"/>
    <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Label FontSize="14"  Content="{TemplateBinding Content}" Name="ZizaMenuItemText" />
        <ControlTemplate.Triggers>
          <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="ZizaMenuItemText" Property="Foreground" Value="#ff0000"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

<StackPanel Height="30" Name="ZizaMenu" Orientation="Horizontal" Margin="0,12,0,0" VerticalAlignment="Top">
  <Label Content="ZIZA" FontSize="11" FontWeight="Bold" Foreground="Black" Height="25" Margin="20,0,10,0" />
  <Button Name="ZizaMenuInteresting" Click="ZizaMenuItemClicked" Content="ИНТЕРЕСНОЕ" Style="{StaticResource ZizaMenuItem}" />
  <Button Name="ZizaMenuBest" Click="ZizaMenuItemClicked" Content="ЛУЧШЕЕ" Style="{StaticResource ZizaMenuItem}" />
  <Button Name="ZizaMenuAuto" Click="ZizaMenuItemClicked" Content="АВТО" Style="{StaticResource ZizaMenuItem}" />
</StackPanel>
private void ZizaMenuItemClicked(object sender, RoutedEventArgs e)
{
    // get label object from template
    Button zizaMenuItem = (Button)sender;
    Label zizaMenuItemText = (Label)zizaMenuItem.Template.FindName("ZizaMenuItemText", zizaMenuItem);
    // set Foreground color for all buttons in menu
    foreach (var item in ZizaMenu.Children)
      if (item is Button)
        ((Label)(item as Button).Template.FindName("ZizaMenuItemText", (item as Button))).Foreground = Brushes.Black;
    // set desired color to clicked button label
    zizaMenuItemText.Foreground = new SolidColorBrush(Color.FromRgb(102, 206, 245));
}

2 个答案:

答案 0 :(得分:2)

这是一个可怕的代码,不会混淆控件模板内的控件。 Template.FindName只是被模板化的控件应该在内部调用以获取其parts,而那些,其他所有内容都应被视为不确定。

如果需要更改属性模板,请绑定它,然后在实例上绑定或设置所述属性。就precedence而言,您需要确保不要创建一个本地值来覆盖触发器(这就是您所做的)。您可以使用Style上的SetterLabel绑定默认Foreground

<Label.Style>
    <Style TargetType="Label">
        <Setter Property="Foreground" Value="{TemplateBinding Foreground}"/>
    </Style>
</Label.Style>

现在您只需设置Foreground本身的ButtonTrigger内部应优先于Setter

答案 1 :(得分:1)

它与依赖属性值优先级有关。本地值的优先级高于模板触发器。

欲了解更多信息,请阅读:http://msdn.microsoft.com/en-us/library/ms743230.aspx