ChristianMurschall
ChristianMurschall

Reputation: 1711

Enabling TextBox with trigger

I want a Textbox to be disabled, except the user hovers with the mouse over it. But this does not seam to work, the Textbox is still not editable if I hover over it. (Yes I know that this is unusual.) What I tried is:

<Border>
    <TextBox Text="Hover to edit me!" IsEnabled="False" >
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Border}, Path=IsMouseOver}" Value="True">
                        <Setter Property="IsEnabled" Value="True" />
                    </DataTrigger>
                    <!-- this does not work either -->
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsMouseOver}" Value="True">
                         <Setter Property="IsEnabled" Value="True" />
                    </DataTrigger>
                    <!-- neither did this -->
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="IsEnabled" Value="True" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
</Border>    

I wonder if it is possible at all using a trigger?

Upvotes: 0

Views: 306

Answers (1)

dymanoid
dymanoid

Reputation: 15227

This is because of the Dependency Property Value Precedence in WPF.

You need to set the IsEnabled property to false in the Style, so the trigger can override the value.

The local value has always a higher priority, so setting IsEnabled="False" directly in the text box will override any style or style trigger value.

Here is a working example:

  <Border>
    <TextBox Text="Text">
      <TextBox.Style>
        <Style TargetType="TextBox">
          <Setter Property="IsEnabled" Value="False"/>
          <Style.Triggers>
            <DataTrigger
                Binding="{Binding IsMouseOver,
                RelativeSource={RelativeSource FindAncestor, AncestorType=Border}}"
                Value="True">
              <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
          </Style.Triggers>
        </Style>
      </TextBox.Style>
    </TextBox>
  </Border>

Upvotes: 3

Related Questions