Events 处理文本框事件,例如ViewModel中更改的文本

Events 处理文本框事件,例如ViewModel中更改的文本,events,mvvm,textbox,Events,Mvvm,Textbox,为了处理视图模型中的按钮单击,我们使用ViewModel属性钩住按钮命令 <Button Command="ButtonCommand"/> class MyViewModel { ICommand _buttonCommand; public MyViewModel() { _buttonCommand=new CommandHandler(() => Buttonfunction(), "true"); } public ICo

为了处理视图模型中的按钮单击,我们使用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();
 }
}

类MyViewModel
{
i命令_按钮命令;
公共MyViewModel()
{
_buttonCommand=newCommandHandler(()=>Buttonfunction(),“true”);
}
公用ICommand按钮命令
{
获取{return\u buttonCommand;}
}
私有无效按钮函数
{//做点什么。}
}
公共类CommandHandler:ICommand
{
私人行动;
私人楼宇可执行;
公共命令处理程序(操作,布尔canExecute)
{
_行动=行动;
_canExecute=canExecute;
}
公共布尔CanExecute(对象参数)
{
返回-可执行;
}
公共事件处理程序CanExecuteChanged;
public void Execute(对象参数)
{
_动作();
}
}
类似地,可以为TextBox事件执行哪些操作。 在.NET3.5中,如何将命令与TextBox事件绑定

<TextBox TextChanged=?/>

必须先将其绑定到属性,然后将该属性的setter用作文本更改事件。 在您的xaml中:

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

实际上应该是
,但总体思路是正确的。谢谢侯赛因。我们如何使用命令和事件来实现这一点?使用命令和事件或如上所述,更好的方法是什么。@Vijay您不能,在MVVM中您拥有这些属性。因此,您不必使用正常事件。可以通过将属性绑定到视图并侦听其更改来创建它们。这就是MVVM的工作原理。别担心,你很快就会习惯的。还有一件事,这些命令并不完全是单击事件。它们是ViewModel的动作,因此它们必须与ViewModel的概念相关。