【发布时间】:2015-05-12 16:00:22
【问题描述】:
我很难理解按钮命令的工作原理。我有这样的东西
{Binding TxtBox} 从模型中获取价值,假设它是“aaa”。我想点击按钮,值应该出现在第二个文本框中(带有{Binding TxtBox2}的那个)。
这是我的 xaml:
<TextBox Text="{Binding TxtBox, Source={StaticResource viewModel}}" />
<TextBox Text="{Binding TxtBox2, Source={StaticResource viewModel}}" />
<Button Command="{Binding ClickCommand}"/>
这是我的视图模型:
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();
}
}
我真的需要这个CommandHandler 课程吗?我从网上复制了代码。
public string TxtBox
{
get { return Model.TxtBoxValue; }
set { Model.TxtBoxValue = value; }
}
public string TxtBox2 { get; set; }
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), _canExecute)); // I believe that when the button is clicked MyAction() is triggered, right?
}
}
private bool _canExecute = true;
public void MyAction()
{
this.TxtBox2 = this.TxtBox; // should something like this work? Because right now it doesn't
}
【问题讨论】:
-
'This is my ViewModel:' 紧随其后的是 ICommand 的实现。我认为这可能只是一个编辑问题,但您可能需要轻推标题以指示哪些部分实际上是您的 ViewModel。
-
不直接相关,但您将希望在某处实现 INotifyPropertyChanged - 请参阅 msdn.microsoft.com/en-us/library/ms743695%28v=vs.110%29.aspx。这将通知 View 对 ViewModel 中的属性的任何更改。 “通常”的方法是创建一个实现 INotifyPropertyChanged 的基类,然后在您的 ViewModels 中从它继承。