2014-09-24 31 views
0

我有一个文本框,并且我已经为它绑定了ctrl键。假设用户在文本框中输入了下面的句子。在光标下方键入并获取文本框当前词

"I love my Country " 

而当前光标位置在单词“国家”内。现在用户只需按下控件(ctrl)键,然后我希望光标位置下的当前单词意味着“国家”将传递给我的视图模型。

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

是否有任何方式通过命令参数传递当前的单词。

+0

'CommandParameter'不允许依赖特性。 – Herdo 2014-09-24 06:48:45

+0

好的。在那种情况下,我是否有其他选择来实现这一目标? – ifti24 2014-09-24 06:50:29

回答

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

@XML爱人:我刚测试过它。绑定CaretIndex总是给我零。我认为caretIndex是一个依赖属性,绑定是不允许的。 – ifti24 2014-09-24 08:39:38

相关问题