禁用WPF按钮悬停效果



标准WPF按钮控件有一个鼠标悬停高亮显示,可以更改控件的颜色。我正在尝试禁用此效果。虽然我在SO上看到了很多涉及XAML更改的问题和答案,但我正试图以100%的编程方式完成这项工作,但我一直未能找到任何解决此问题的方法。

我没有任何XAML,因为我的WPF应用程序动态地向表单添加了一个(派生的(按钮控件列表。派生的按钮类没有任何XAML。

var button = new CustomButton(); // Inherits System.Windows.Controls.Button
button.Content = textBlock;  // System.Windows.Controls.TextBlock
// other various property changes to the custom button removed
button.Focusable = false;
grid.Children.Add(button);

该按钮与我的自定义代码配合得很好,但我无法删除鼠标悬停效果。这尤其糟糕,因为它是在触摸屏上使用的,所以最后一次触摸的按钮会保留鼠标悬停效果,直到按下另一个按钮或用户单击窗口的未使用区域。

多亏了评论中的Kostas,我现在知道我需要创建一个全局样式,并将其应用于我的自定义控件,然而,根据我最初的问题,所有这样做的例子都涉及XAML,所以我的问题应该更具体地说,如何在没有鼠标悬停触发器的情况下完全通过编程创建全局样式?

我缺少的一块拼图是,样式的XAML不需要进入按钮类,而是进入父窗口XAML。样式然后被添加到按钮类中,就像它被添加到窗口中一样:

<Window x:Class="SomeOrg.SomeApp.WpfInterface.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfInterface"
mc:Ignorable="d"
Title="SomeApp" Height="450" Width="800"
Background="#ffffffe1">
<Window.Resources>
<Style x:Key="MyButton" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border" BorderThickness="0" BorderBrush="Black" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid x:Name="grid" HorizontalAlignment="Stretch" Height="Auto" Margin="10,10,10,10" VerticalAlignment="Stretch"
Width="Auto" Background="#ffffffe1"/>
</Grid>
</Window>

在父窗口的代码中,自定义按钮被添加到窗口中,上面的样式(MyButton(被应用如下:

var button = new CustomButton();
customButton.Style = (Style) this.Resources["MyButton"];
grid.Children.Add(button);

最新更新