在 ViewModel 中处理 Text_changed 等 TextBox 事件
Handle TextBox event such as Text_changed in ViewModel
为了处理 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=?/>
您必须先将其绑定到 属性,然后使用 属性 的 setter 作为您的文本更改事件。
在你的 xaml:
<TextBox Text="{Binding Name}" />
在你的视图模型中
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
yourTextChangeEvent();
}
}
为了处理 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=?/>
您必须先将其绑定到 属性,然后使用 属性 的 setter 作为您的文本更改事件。 在你的 xaml:
<TextBox Text="{Binding Name}" />
在你的视图模型中
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
yourTextChangeEvent();
}
}