wpf更改KeyBinding手势上的文本框文本

时间:2018-05-24 01:13:24

标签: c# wpf key-bindings ivalueconverter

我如何使用MVVM模式解决这个问题,而我正在使用Devexpress MVVM。我的形式有很多文本框。

当用户按下Ctrl+B并且文本框的当前文字为null""

时,我需要将文本框文本设置为“[空白]”

但我正在寻找一种方法来使用IValueConverter,如果可能的话

我有一个与此类似的课程

public class BlankText : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (string.IsNullOrEmpty(value.ToString()))
                return "[blank]";
            else
                return value;
        }
    }

我在资源中有这段代码

    <UserControl.Resources>
        <c:BlankText x:Key="BlankText"/>
    </UserControl.Resources>

这是我的TextBox

           <TextBox Text="{Binding District}"  >
                <TextBox.InputBindings>
                    <KeyBinding Gesture="Ctrl+B">
                    </KeyBinding>
                </TextBox.InputBindings>
            </TextBox>

但我的问题是如何在按键上调用它?我做得对吗?

1 个答案:

答案 0 :(得分:1)

要使用KeyBinding执行操作,您无法使用IValueConverterIValueConverter用于转换值,而不是执行操作。您需要的是定义一个实现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;
}

然后创建此类的实例并将其附加到ViewModel,以便KeyBinding可以访问它:

<TextBox Text="{Binding District}">
    <TextBox.InputBindings>
        <KeyBinding Gesture="Ctrl+B" Command="{Binding MyBlankCommand}" CommandParameter="District"/>
    </TextBox.InputBindings>
</TextBox>

当用户按下键盘快捷键时,将文本更改为“[空白]”是一种奇怪的UX模式。我建议在文本框中添加一个占位符。

相关问题