的CommandParameter值這是我的看法(TypeAheadTextBox.xaml)如何從視圖視圖模型
<TextBox x:Name="textBox" Width="300" Text="{Binding SomeText, UpdateSourceTrigger=PropertyChanged}" TextChanged="textBox_TextChanged_1" SelectionChanged="textBox_SelectionChanged">
<TextBox.InputBindings>
<KeyBinding Command="{Binding LeftCtrlKeyPressed, Mode=TwoWay}" Key="Space" Modifiers="Control" />
<KeyBinding Key="Down" Command="{Binding TextBoxDownArrow, Mode=TwoWay}" />
</TextBox.InputBindings>
</TextBox>
這是我的看法CS文件(TypeAheadTextBox.xmal.cs)
public partial class TypeAheadControl
{
public TypeAheadControl()
{
InitializeComponent();
}
private void textBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
SetCommandParameter(sender);
}
private void textBox_SelectionChanged(object sender, RoutedEventArgs e)
{
SetCommandParameter(sender);
}
private void SetCommandParameter(object sender)
{
TextBox textBox = sender as TextBox;
if (textBox != null && textBox.Text.Length > 0)
{
KeyBinding kb = textBox.InputBindings[0] as KeyBinding;
if (kb != null)
{
string[] words = textBox.Text.Split(new char[] { ' ' });
if (textBox.CaretIndex == textBox.Text.Length)
{
//return last word
kb.CommandParameter = words[words.Length - 1];
Console.WriteLine(words[words.Length - 1]);
}
else
{
int charCount = 0;
foreach (string word in words)
{
charCount += word.Length;
if (charCount >= textBox.CaretIndex)
{
kb.CommandParameter = word;
Console.WriteLine(word);
break;
}
}
}
}
}
}
}
這是我視圖模型類(的一部分)
private DelegateCommand _leftCtrlKeyPressed;
public ICommand LeftCtrlKeyPressed
{
get
{
if (_leftCtrlKeyPressed == null)
{
_leftCtrlKeyPressed = new DelegateCommand(CtrlKeyDetected);
}
return _leftCtrlKeyPressed;
}
set { }
}
public void CtrlKeyDetected()
{
Console.WriteLine("Test=====>>" + CurrentWord);
}
我的問題:
現在我要訪問的文本框在我的ViewModel deligateCommand鍵綁定命令參數值行動
CtrlKeyDetected( )。
有人可以告訴我怎麼做到這一點。
該程序實際上做了什麼?
假設您在文本框中記下了一些文本,並將光標放在單詞上,我的目標是在當前光標位置下獲取當前單詞。只要用戶按下ctrl +空格鍵,我想要獲取命令綁定方法中的值。
您是否需要命令參數中的最後一個單詞? – pushpraj 2014-09-25 06:44:36
沒有。光標下的單詞。 – ifti24 2014-09-25 06:50:13
@默認:你說得對。委託命令的通用版本解決了我的問題。 – ifti24 2014-09-26 09:07:53