【发布时间】:2012-09-04 11:23:18
【问题描述】:
我正在尝试将 ViewModel 中的变量作为参数发送到命令。命令如下所示:
public class EditPersonCommand : ICommand
{
private bool _CanExecute = false;
public bool CanExecute(object parameter)
{
PersonModel p = parameter as PersonModel;
CanExecuteProperty = (p != null) && (p.Age > 0);
return CanExecuteProperty;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter) { }
private bool CanExecuteProperty
{
get { return _CanExecute; }
set
{
if (_CanExecute != value)
{
_CanExecute = value;
EventHandler can_execute = CanExecuteChanged;
if (can_execute != null)
{
can_execute.Invoke(this, EventArgs.Empty);
}
}
}
}
}
ViewModel 如下所示:
public class PersonViewModel : ViewModelBase
{
private PersonModel _PersonModel;
private EditPersonCommand _EditPersonCommand;
///<remarks>
/// must use the parameterless constructor to satisfy <Window.Resources>
///</remarks>
public PersonViewModel()
: this(new PersonModel())
{
}
public PersonViewModel(PersonModel personModel)
{
_PersonModel = personModel;
}
public ICommand EditPersonCommand
{
get
{
if (_EditPersonCommand == null)
{
_EditPersonCommand = new EditPersonCommand();
}
return _EditPersonCommand;
}
}
}
xaml 如下所示:
<Button Content="Edit" HorizontalAlignment="Right" Height="20" Width="80"
Command="{Binding EditPersonCommand}"
CommandParameter="{Binding _PersonModel}" />
我尝试在 ViewModel 中创建一个属性,而不是使用私有局部变量名称,但这也不起作用。 object parameter 在对CanExecute 的调用中始终显示null,并且该按钮从不启用。如果我将CommandParameter 值更改为Hello,那么我会在对CanExecute 的调用中收到Hello,所以我不确定为什么该变量不起作用。任何帮助将不胜感激。
更新:我也尝试过为模型创建一个公共属性(我真的不想公开模型,只是尝试看看它是否有效,但它没有)。
// Added this to the ViewModel
public PersonModel PersonModelProp
{
get
{
return _PersonModel;
}
set
{
_PersonModel = value;
OnPropertyChanged("PersonModelProp");
}
}
并将 xaml 更改为:
<Button Content="Edit" HorizontalAlignment="Right" Height="20" Width="80"
Command="{Binding EditPersonCommand}"
CommandParameter="{Binding PersonModelProp}" />
但仍然没有运气。 ViewModel 确实实现了INotifyPropertyChanged
【问题讨论】:
-
我总是绑定属性
public,我想他们一定是但不确定。 -
不是问题的原因,但是从
CanExecute提升CanExecuteChanged是错误的。当调用者再次调用CanExecute时,应该引发CanExecuteChanged。根据您当前的CanExecute实现,当一个人的年龄发生变化时,您应该提出CanExecuteChanged,但您也可能根本不提出该事件而侥幸。 -
你试过tracing吗?你看到了什么错误?
标签: c# wpf mvvm command commandparameter