1

I am looking for a way to show the Caret in a TextBox when IsMouseOver="True". The solution using FocusManager.IsFocusScope="True" as mentioned here does not seem to work.

Is there a way to show the Caret without having to click inside the TextBox?


MWE:

<Window x:Class="WpfApp11.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <Style BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="FocusManager.IsFocusScope" Value="True" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <TextBox Width="300" Height="22" Text="Hello World" />
    </Grid>
</Window>

A TextBox displaying the Caret after clicking on it. I want the Caret to show already on mouse over.

enter image description here

Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65
  • what do you want to do exactly? replace the mousecursor with a carret or...? – Denis Schaf Mar 04 '21 at 12:44
  • @DenisSchaf when you click in a `TextBox`, a blinking Caret will show. I want to show the blinking Caret when the mouse is over the `TextBox` already, not only after clicking – Thomas Flinkow Mar 04 '21 at 12:45
  • uh thats a though one then... i guess youd have to download the original textbox style with the template and remove the trigger that hides it – Denis Schaf Mar 04 '21 at 13:02

1 Answers1

4

If you want to set focus, then you need to use FocusedElement (credits):

<Style BasedOn="{StaticResource {x:Type TextBox}}"
       TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver"
                 Value="True">
            <Setter Property="FocusManager.FocusedElement"
                    Value="{Binding RelativeSource={RelativeSource Self}}" />
        </Trigger>
    </Style.Triggers>
</Style>

If you want caret to be initially at the end then consider to initialize all textboxes like this (credits):

<TextBox CaretIndex="{x:Static system:Int32.MaxValue}" ... />

where system is defined like this:

<Window xmlns:system="clr-namespace:System;assembly=mscorlib" ... />
Sinatr
  • 20,892
  • 15
  • 90
  • 319