Tushar Kukreti Tushar Kukreti - 4 months ago 37
C# Question

Change mouse cursor to "stop" pointer on hover on disabled button in WPF

I want the mouse cursor to change to a "stop" pointer when I hover over the button, if it's disabled. In case of an enabled button, the following code is working but it's not applicable to a disabled button:

XAML:

<Button x:Name="Button1" Content="Button1" Isenabled="false" />


CS:

Button1.MouseEnter += (s, e) => Mouse.OverrideCursor = Cursors.No;

Answer

Since you won't be able to trigger events with a disable control, I suggest placing a transparent rectangle over it, which will handle that for you:

<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>

The rectangle is collapsed when button is not enabled, so that it would allow button events to trigger. When the button is enabled, rectangle becomes visible (with 0 opacity and transparent background) and causes No cursor to appear when moused over.