如何解决为什么我的 Style.trigger 事件对我的 WPF Datagrid 不起作用?
我在 WPF 中有一个 DataGrid,并在 setter 中为它创建了一个 ControlTemplate。在我创建这个 ControlTemplate 之前,我的 Style.trigger 与 IsMouseOver 事件完美配合。但是在放置 Controltemplate 之后它不再工作了。这是我的代码:
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="#292F3B"/>
<Setter Property="Foreground" Value="LightBlue"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Height" Value="30"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="BorderThickness" Value="0,2,0" />
<Setter Property="BorderBrush" Value="#333333"/>
<Setter Property="Padding" Value="10 0 0 0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
<Border Background="#242A36">
<Border BorderThickness="1"
CornerRadius="6"
Background="#2D2D30"
Padding="10,0"
Margin="2">
<ContentPresenter/>
</Border>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
所以我只希望 IsMouseOver 效果与 ControlTemplate 一起使用。
解决方法
将您的 <Style.Triggers>
现在作为 <ControlTemplate.Triggers>
移动到 ControlTemplate 中,您应该会看到它再次改变背景。但是您必须使用 Target
属性确定背景的目标,因为 WPF 不够聪明,无法知道您在谈论哪种背景。
这是一个例子:
<Window.Resources>
<Style x:Key="mystyle" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="#292F3B"/>
<Setter Property="Foreground" Value="LightBlue"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Height" Value="30"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="BorderThickness" Value="0,2,0" />
<Setter Property="BorderBrush" Value="#333333"/>
<Setter Property="Padding" Value="10 0 0 0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
<Border x:Name="border" Background="#242A36">
<Border BorderThickness="1"
CornerRadius="6"
Background="#2D2D30"
Padding="10,0"
Margin="2">
<ContentPresenter/>
</Border>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<DataGrid CanUserAddRows="True" ItemsSource="{Binding Stuff}">
<DataGrid.Columns>
<DataGridTextColumn HeaderStyle="{StaticResource mystyle}" Header="Name"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
将鼠标悬停在标题上时的效果如下。
注意:我不知道你到底想改变什么颜色,所以我只是选择了你定义的外边框
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。