0
votes

I have a textbox and I have binded ctrl key for it. Suppose a user has typed the below sentence in the textbox.

"I love my Country "

And the current cursor positin is inside the word "Country". Now the users just pressed the control(ctrl) key and then I want that the current word under the cursor position that means "Country" will be passed to my view 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>  

Is there any way to pass that current word through command parameter.

1
CommandParameter doesn't allow dependency properties.Herdo
Ok. In that case do I have any other option to achieve the goal?ifti24

1 Answers

0
votes

You can use a MultiValueConverter. Pass both the text and Caret Index o the converter. Do string manipulation and return the word from converter.

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 looks like this,

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