问题描述
我正在寻找一种在 TextBox
时在 IsMouSEOver="True"
中显示插入符号的方法。前面提到的使用 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
。我希望插入符号在鼠标悬停时显示。
解决方法
如果要设置焦点,则需要使用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" ... />