【问题标题】:wpf Change the text of Textbox on KeyBinding Gesturewpf 在 KeyBinding Gesture 上更改文本框的文本
【发布时间】:2018-05-24 01:13:24
【问题描述】:

我如何使用 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 Text="{Binding District}"  >
                <TextBox.InputBindings>
                    <KeyBinding Gesture="Ctrl+B">
                    </KeyBinding>
                </TextBox.InputBindings>
            </TextBox>

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

【问题讨论】:

    标签: c# wpf key-bindings ivalueconverter


    【解决方案1】:

    要使用KeyBinding 执行操作,您不能使用IValueConverterIValueConverters 用于转换值,而不是执行操作。您需要定义一个实现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 模式。我建议改为在文本框中添加一个占位符。

    【讨论】:

    • 我已经想到了这个解决方案,但是有了这个。我需要为每个文本框设置一个命令
    • @mecocopy 您可以为每个文本框使用命令的单个实例;是什么阻止了你?
    • 然后在我的指挥下。我怎么知道传入了哪个 Binding?为了知道我将设置为“[空白]”的属性?每个文本框文本都绑定到一个属性
    • 我修改了我的帖子以使用反射,它允许这种模式工作。但是,您现在需要在实例化时将 ViewModel 的实例传递给命令。
    猜你喜欢
    • 2014-07-12
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多