从以下触发器中只有Foreground Setter工作正常。我不明白为什么。
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
感谢您的帮助。
答案 0 :(得分:2)
WPF中的按钮具有默认控件模板。覆盖Button的默认行为的正确方法是覆盖默认控件模板。这可以通过以下类似的方式完成:
<Button Width="100" Height="50" Content="Click Me!">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="bdr_main" CornerRadius="20" Margin="4" BorderThickness="1" BorderBrush="Black" Background="LightGray">
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Margin="8,6,8,6" ContentSource="Content" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bdr_main" Property="Background" Value="LightGreen"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="bdr_main" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
找到@ http://harishasanblog.blogspot.com/2011/02/ismouseover-trigger-not-working-in-wpf.html
希望它有所帮助!
答案 1 :(得分:2)
尝试使用controltemplate上的触发器。
<ResourceDictionary>
<Style x:Key="TestButton" TargetType="Button">
<Setter Property="Height" Value="30" />
<Setter Property="Width" Value="30" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Green" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Purple" />
</Trigger>
</ControlTemplate.Triggers>
<Grid>
<Rectangle Fill="{TemplateBinding Foreground}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
答案 2 :(得分:2)
这不起作用的原因是因为默认的Button模板使用ButtonChrome绘制边框和背景并处理鼠标悬停和禁用等状态,具体取决于Windows主题(例如Windows XP样式,Windows 7样式) )。
为了允许应用触发器,您需要定义一个自定义Button模板,该模板使用标准的可设置样式的WPF元素,如Border,而不是ButtonChrome。这是一个简单的工作示例:
<Button Content="button">
<Button.Style>
<Style TargetType="Button">
<Setter Property="BorderThickness" Value="3" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Property=Background}"
BorderBrush="{TemplateBinding Property=BorderBrush}"
BorderThickness="{TemplateBinding Property=BorderThickness}">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="BorderBrush" Value="Green" />
<Setter Property="Foreground" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>