【问题标题】:Handle TextBox event such as Text_changed in ViewModel处理 ViewModel 中的 TextBox 事件,例如 Text_changed
【发布时间】:2015-11-19 04:38:18
【问题描述】:

为了处理 View-model 中的 Button Click,我们将 Button-Command 与 ViewModel 属性挂钩。

<Button Command="ButtonCommand"/>


class MyViewModel
{
   ICommand _buttonCommand;
   public MyViewModel()
   {
     _buttonCommand=new CommandHandler(() => Buttonfunction(), "true");
   }

   public ICommand ButtonCommand
   {
    get{ return _buttonCommand;}    
   }

   private void Buttonfunction
   { //do something. }
}

public class CommandHandler : ICommand
{
 private Action _action;
 private bool _canExecute;
 public CommandHandler(Action action, bool canExecute)
 {
    _action = action;
    _canExecute = canExecute;
 }

 public bool CanExecute(object parameter)
 {
    return _canExecute;
 }

 public event EventHandler CanExecuteChanged;

 public void Execute(object parameter)
 {
    _action();
 }
}

同样可以为 TextBox 事件做些什么。 我们如何在 .NET 3.5 中将命令与 TextBox 事件绑定。

<TextBox TextChanged=?/>

【问题讨论】:

    标签: events mvvm textbox


    【解决方案1】:

    您必须先将它绑定到一个属性,然后将该属性的设置器用作您的文本更改事件。 在您的 xaml 中:

    <TextBox Text="{Binding Name}" />
    

    在您的视图模型中

    private string _name;
    
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            yourTextChangeEvent();
        }
    }
    

    【讨论】:

    • 其实应该是&lt;TextBox Text="{Binding Name}" /&gt;,不过大体思路是对的。
    • 谢谢侯赛因。我们如何通过命令和事件来实现这一点?以及使用命令和事件或如上所述的更好的方法。
    • @Vijay 你不能,在 MVVM 中你拥有这些属性。所以你不必使用正常的事件。您可以通过将属性绑定到您的视图并监听它的更改来创建它们。这就是 MVVM 的工作方式。别担心,你很快就会习惯的。还有一件事,这些命令不完全是点击事件。它们是您的 ViewModel 的操作,因此它们必须与您的 ViewModel 的概念相关。
    猜你喜欢
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多