在我的视图中,我尝试通过以下XAML将事件绑定到Enter键:
<TextBox x:Name="txtFields" Text="{Binding FieldsTextProperty, UpdateSourceTrigger=PropertyChanged}" Height="23" TextWrapping="NoWrap" Background="#FFCBEECD" AcceptsReturn="False" >
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding AddFieldCommand}"></KeyBinding>
</TextBox.InputBindings>
</TextBox>
我的ViewModel中存在AddFieldCommand
作为属性:
public ICommand AddFieldCommand { get; private set; }
在ViewModel构造函数中,存在以下RelayCommand
。
AddFieldCommand = new RelayCommand(AddField);
从RelayCommand
调用方法AddField
。
public void AddField()
{
Console.WriteLine("AddField Method")
}
这不起作用 - 从不调用AddField方法。有人可以帮忙吗?
答案 0 :(得分:1)
我想知道.InputBindings是否在这种情况下不起作用。键盘输入处理可能被TextBox劫持。
假设您希望坚持使用MVVM模式并避免代码隐藏中的事件处理代码,我可能会选择创建TextBox的自定义实现 - 将其称为“SubmitTextBox”&#39 ;
自定义SubmitTextBox可以自动挂接到PreviewKeyDown事件,并监视Enter键。
您可以通过添加ICommand DP来进一步遵守MVVM来处理“提交”。事件
像这样......
public class SubmitTextBox : TextBox
{
public SubmitTextBox()
: base()
{
PreviewKeyDown += SubmitTextBox_PreviewKeyDown;
}
private void SubmitTextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter)
{
if (this.SubmitCommand != null && this.SubmitCommand.CanExecute(this.Text))
{
// Note this executes the command, and returns
// the current value of the textbox.
this.SubmitCommand.Execute(this.Text);
}
}
}
/// <summary>
/// The command to execute when the text is submitted (Enter is pressed).
/// </summary>
public ICommand SubmitCommand
{
get { return (ICommand)GetValue(SubmitCommandProperty); }
set { SetValue(SubmitCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for SubmitCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SubmitCommandProperty =
DependencyProperty.Register("SubmitCommand", typeof(ICommand), typeof(SubmitTextBox), new PropertyMetadata(null));
}
你的XAML最终看起来像这样:
<custom:SubmitTextBox
x:Name="txtFields"
Text="{Binding FieldsTextProperty}"
SubmitCommand="{Binding AddFieldCommand}"
Height="23"
TextWrapping="NoWrap"
Background="#FFCBEECD" />
希望有所帮助:)
更新:为了澄清,我创建的SubmitCommand返回文本框中的当前文本作为参数。为了将其与MVVM-Light工具包一起使用,您需要创建一个可以接受类型&#39;字符串的RelayCommand。
public RelayCommand<string> AddFieldCommand { get; private set; }
public ViewModelConstructor()
{
AddFieldCommand = new RelayCommand<string>(AddField);
}
private void AddField(string text)
{
// Do something
}
我希望能够解决问题:)