【问题标题】:WPF TextBox show Caret on MouseOverWPF 文本框在 MouseOver 上显示插入符号
【发布时间】:2021-03-04 12:28:29
【问题描述】:

我正在寻找一种在IsMouseOver="True" 时在TextBox 中显示插入符号的方法。使用FocusManager.IsFocusScope="True" 提到的here 的解决方案似乎不起作用。

有没有一种无需在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>

TextBox 在单击后显示插入符号。我希望插入符号已经显示在鼠标悬停上。

【问题讨论】:

  • 你到底想做什么?用 carret 替换鼠标光标或...?
  • @DenisSchaf 当您单击TextBox 时,将显示一个闪烁的插入符号。当鼠标已经在TextBox 上时,我想显示闪烁的插入符号,而不仅仅是在单击之后
  • 呃,那是一个虽然...我猜你必须下载带有模板的原始文本框样式并删除隐藏它的触发器

标签: c# wpf textbox caret


【解决方案1】:

如果要设置焦点,则需要使用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>

如果您希望插入符号最初位于末尾,请考虑像这样初始化所有文本框 (credits):

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

system 的定义如下:

<Window xmlns:system="clr-namespace:System;assembly=mscorlib" ... />

【讨论】:

  • 不错,但它会将 carret 设置为索引 0。
  • @user2250152,这不会改变CaretIndex,如果它在焦点丢失之前位于末尾,它将停留在末尾。
猜你喜欢
  • 2011-01-08
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多