【发布时间】:2013-01-05 12:57:22
【问题描述】:
我有,
private ICommand AddCommand = new RCommand(p => true, p => Add() );
private void Add()
{
emp = new Employee();
DetailsEntryGrid.DataContext = emp;
EnableControls();
tBoxID.Focus();
tBoxID.SelectAll();
//throw new NotImplementedException();
}
vs2010 引发编译时错误,即“p”不能指向非静态字段,并且我无法访问网格和文本框 ..这些控件是 wpf .. 我也无法为员工创建对象..
Rcommand 类是..
public class RCommand : ICommand
{
readonly Predicate<object> _CanExecute;
readonly Action<object> _Execute;
public RCommand(Action<object> exe) : this(null,exe)
{
}
public RCommand(Predicate<object> predicate, Action<object> action)
{
if (predicate == null)
throw new ArgumentNullException("execute must be provided");
_Execute = action;
_CanExecute = predicate;
}
public bool CanExecute(object parameter)
{
return _CanExecute == null ? true : _CanExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_Execute(parameter);
}
}
我想访问那个 Add() 方法,然后我想访问文本框和数据网格。我应该怎么做?
或者我应该如何拥有 RCommand 类..?
【问题讨论】:
-
在 MVVM 中,ViewModel 不应该对 View 有任何了解。使用 ChrisF 建议的事件。请注意,您在构造函数中的 null 检查是错误的:
if (predicate == null)应该是if (action == null) -
@weston - 感谢您指出...
-
@weston - 你能给出一个示例代码来从视图模型中触发一个事件并在视图中处理它吗?
-
这是一个很好的 MVVM visualstudiogallery.msdn.microsoft.com/… 包括事件“聚合”的教程。
-
@weston - 感谢您的链接...
标签: wpf static wpf-controls wpfdatagrid relaycommand