为了执行操作,请使用
KeyBinding
,您不能使用
IValueConverter
.
伊瓦卢埃科弗特
s用于转换值,而不是执行操作。您需要定义一个实现
ICommand
,然后将该类的实例分配给
KeyBinding.Command
.
public class BlankCommand : ICommand
{
public MyViewModel ViewModel { get; }
public BlankCommand(MyViewModel vm)
{
this.ViewModel = vm;
}
public void Execute(object parameter)
{
// parameter is the name of the property to modify
var type = ViewModel.GetType();
var prop = type.GetProperty(parameter as string);
var value = prop.GetValue(ViewModel);
if(string.IsNullOrEmpty(value))
prop.SetValue(ViewModel, "[blank]");
}
public boolean CanExecute(object parameter) => true;
public event EventHandler CanExecuteChanged;
}
然后创建该类的实例并将其附加到您的视图模型,以便键绑定可以访问它:
<TextBox Text="{Binding District}">
<TextBox.InputBindings>
<KeyBinding Gesture="Ctrl+B" Command="{Binding MyBlankCommand}" CommandParameter="District"/>
</TextBox.InputBindings>
</TextBox>
然而,当用户按下键盘快捷键时,将文本改为说“[空白]”是一种奇怪的UX模式。我建议在文本框中添加一个占位符。