【问题标题】:Key bnding and get textbox current word under the cursor键绑定并获取光标下的文本框当前单词
【发布时间】:2014-09-24 06:45:31
【问题描述】:

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

"I love my Country "

并且当前光标位置在单词“Country”内。现在用户只需按下 control(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>  

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

【问题讨论】:

  • CommandParameter 不允许依赖属性。
  • 好的。在这种情况下,我还有其他选择来实现目标吗?

标签: c# wpf mvvm


【解决方案1】:

您可以使用 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>

【讨论】:

  • @XML Lover:我刚刚测试过了。绑定 CaretIndex 总是给我零。我认为 caretIndex 是一个依赖属性,不允许绑定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
相关资源
最近更新 更多