键绑定并获取光标下的文本框当前单词

时间:2014-09-24 06:45:32

标签: c# wpf mvvm

我有一个文本框,我为它绑定了ctrl键。假设用户在文本框中键入了以下句子。

"I love my Country "

当前光标positin位于“Country”字样中。现在用户只需按下控制(ctrl)键,然后我想要将光标位置下的当前单词表示“Country”传递给我的视图模型。

    <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>  

有没有办法通过命令参数传递当前的单词。

1 个答案:

答案 0 :(得分:0)

您可以使用MultiValueConverter。通过转换器的文本和插入索引。执行字符串操作并从转换器返回单词。

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>
相关问题