键入bnding并获取光标下的文本框当前单词
本文关键字:文本 单词 bnding 获取 光标 键入 | 更新日期: 2023-09-27 18:24:05
我有一个文本框,并为它绑定了ctrl键。假设用户在文本框中键入了以下句子。
"I love my Country "
当前光标位置在单词"Country"内。现在,用户只需按下control(ctrl)键,然后我希望光标位置下的当前单词,即"Country",将传递给我的视图Model。
<TextBox x:Name="textBox" Width="300" Text="{Binding SomeText, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="LeftCtrl" Command="{Binding LeftCtrlKeyPressed, Mode=TwoWay}" CommandParameter="" />
</TextBox.InputBindings>
</TextBox>
有什么方法可以通过命令参数传递当前单词吗。
您可以使用MultiValueConverter。将文本和Caret Index都传递到转换器。执行字符串操作并从转换器返回单词。
public class StringConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = values[0].ToString();
int index = (int)values[1];
if (String.IsNullOrEmpty(text))
{
return null;
}
int lastIndex = text.IndexOf(' ', index);
int firstIndex = new String(text.Reverse().ToArray()).IndexOf(' ', index);
return text.Substring(firstIndex, lastIndex - firstIndex);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML看起来像这样,
<TextBox.InputBindings>
<KeyBinding Key="LeftCtrl"
Command="{Binding LeftCtrlKeyPressed}">
<KeyBinding.CommandParameter>
<MultiBinding Converter="{StaticResource StringConverter}">
<Binding ElementName="txt"
Path="Text" />
<Binding ElementName="txt"
Path="CaretIndex" />
</MultiBinding>
</KeyBinding.CommandParameter>
</KeyBinding>
</TextBox.InputBindings>