【问题标题】:KeyBinding to a function in code behind? WPF/MVVMKeyBinding到代码后面的函数? WPF/MVVM
【发布时间】:2022-08-19 01:43:57
【问题描述】:

我有一个文本框,当用户在键盘上按 Enter 时,文本框中的值会得到“确认”,并且字符串被格式化为正确的小数位数。

因此,如果文本框应该有 1 位小数,并且用户输入“30”而没有任何小数并按 Enter,则文本框会自动更新为“30.0”。

问题是发生这种情况时 CaretIndex 位于位置 0。如果我在 0 之后使用插入符号按 Enter 键,例如 \"30|\",那么它会重置为 \"|30.0\" 而不是 \"30.0|\" 我想要的那样。

我有一个在文本框中按下回车键时触发的命令。但是,该命令位于视图模型内部,我不应该在视图模型中触摸视图事物(插入符号)。那么我应该怎么做呢?

我正在考虑而不是绑定到视图模型中的命令,而是绑定到视图中的函数(代码后面),然后从该函数中我在 VM 中提出命令并设置插入符号,如下所示:

    private void EnterPressed()
    {
        ((ParamTextNodeVM)DataContext).EnterCmd.Execute(null);
        ValueBox.CaretIndex = ValueBox.Text.Length;
    }

但是,这不起作用:

   <TextBox>
       <TextBox.InputBindings>
           <KeyBinding Key=\"Enter\" Command=\"{Binding EnterPressed}\"/>
       </TextBox.InputBindings>
    </TextBox>

我如何将 \"Command\" 绑定到后面代码中的 \"EnterPressed\"?

    标签: binding command code-behind key-bindings


    【解决方案1】:

    绑定到后面代码中的函数会起作用,但会违反 MVVM 模式。中继命令允许您将视图中的命令绑定到视图模型。

     /// <summary>
    /// A basic command that runs an Action
    /// </summary>
    public class RelayCommand : ICommand
    {
        #region Private Members
    
        /// <summary>
        /// The action to run
        /// </summary>
        private Action mAction;
    
        #endregion
    
        #region Public Events
    
        /// <summary>
        /// The event thats fired when the <see cref="CanExecute(object)"/> value has changed
        /// </summary>
        public event EventHandler CanExecuteChanged = (sender, e) => { };
    
        #endregion
    
        #region Constructor
    
        /// <summary>
        /// Default constructor
        /// </summary>
        public RelayCommand(Action action)
        {
            mAction = action;
        }
    
        #endregion
    
        #region Command Methods
    
        /// <summary>
        /// A relay command can always execute
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        /// <summary>
        /// Executes the commands Action
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            mAction();
        }
    
        #endregion
    }
    

    在视图模型本身中,您需要将命令声明为参数

    public ICommand EnterPressedCommand { get; set; }
    

    最后,在 ViewModel 的构造函数中,您需要将命令分配给函数

    EnterPressedCommand = new RelayCommand(() => EnterPressed());
    

    这应该允许从视图中触发命令,并执行您的 EnterPressed 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 2013-06-03
      • 2018-11-24
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多