使插入符号(光标)停止闪烁

时间:2019-07-25 02:18:33

标签: c# .net wpf

如何在WPF中使TextBox中的光标停止闪烁?

我已经尝试通过一项MouseDown操作在父项上进行this.Focus();事件,该操作无效。

1 个答案:

答案 0 :(得分:0)

您可以使用HideCaret方法来实现。但是,由于WPF应用程序无法为您提供TextBox控件的句柄(它仅为Window提供句柄),因此我们无法使用HideCaret。

但是,我们可以使用WPF emulate效果。要实现此目的的第一步是禁用实际的插入符号。可以通过将颜色更改为透明来完成。

<TextBox x:Name="txtName" CaretBrush="Transparent" />

下一步涉及使用“画布和边框”来模拟光标。

<Grid>
    <TextBox x:Name="txtName" CaretBrush="Transparent" />
    <Canvas>
        <Border x:Name="Caret" Visibility="Collapsed" Canvas.Left="0" Canvas.Top="0" Width="1" Height="15" Background="Black"/>
    </Canvas>
</Grid>

您需要确保画布与文本框重叠

并在代码后方

txtName.SelectionChanged += (sender, e) => MoveCustomCaret();
txtName.LostFocus += (sender, e) => Caret.Visibility = Visibility.Collapsed;
txtName.GotFocus += (sender, e) => Caret.Visibility = Visibility.Visible;

将MoveCustomCaret定义为

    private void MoveCustomCaret()
    {
        var caretLocation = txtName.GetRectFromCharacterIndex(txtName.CaretIndex).Location;

        if (!double.IsInfinity(caretLocation.X))
        {
            Canvas.SetLeft(Caret, caretLocation.X);
        }

        if (!double.IsInfinity(caretLocation.Y))
        {
            Canvas.SetTop(Caret, caretLocation.Y);
        }
    }

样品

enter image description here

相关问题