当我将鼠标悬停在按钮上时,如果它被禁用,我希望鼠标光标变为"停止"指针.如果启用了按钮,则以下代码正在运行,但它不适用于禁用的按钮:
XAML:
<Button x:Name="Button1" Content="Button1" Isenabled="false" />
Run Code Online (Sandbox Code Playgroud)
CS:
Button1.MouseEnter += (s, e) => Mouse.OverrideCursor = Cursors.No;
Run Code Online (Sandbox Code Playgroud)
由于您无法使用禁用控件触发事件,我建议在其上放置一个透明矩形,它将为您处理:
<Button x:Name="Button1" IsEnabled="False"/>
<Rectangle Opacity="0" Fill="Transparent">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=Button1, Path=IsEnabled}"
Value="False">
<Setter Property="Cursor" Value="No"/>
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
Run Code Online (Sandbox Code Playgroud)
未启用按钮时,矩形将折叠,以便触发按钮事件.启用该按钮后,矩形变为可见(0不透明度和透明背景),并在鼠标悬停时显示无光标.
编辑:
根据评论,这是一个工作样本(也试图解决OP与启用按钮取消行为的问题):
<Window x:Class="WpfApplication.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:WpfApplication"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center"
HorizontalAlignment="Center">
<!-- Regular Button-->
<Button Width="120" Height="22" Margin="5"/>
<!--Custom Button-->
<Grid Width="120" Height="22" Margin="5">
<Button x:Name="Button1" IsEnabled="False"/>
<Rectangle Opacity="0" Fill="Transparent">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=Button1, Path=IsEnabled}"
Value="False">
<Setter Property="Cursor" Value="No"/>
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
</Grid>
</StackPanel>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
这是演示:
我建议使用类似的XAML创建自定义控件,或者至少创建一个模板,以便您可以重复使用它.