代码之家  ›  专栏  ›  技术社区  ›  mecocopy

WPF更改键绑定手势上文本框的文本

  •  0
  • mecocopy  · 技术社区  · 6 年前

    我如何使用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>
    

    但我的问题是我怎样才能在按键时调用它?我做得对吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   laptou    6 年前

    为了执行操作,请使用 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模式。我建议在文本框中添加一个占位符。