我正在尝试将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
5条答案
按热度按时间vof42yt11#
CommandParameter是否始终为null,或者您是否只在第一次执行时检查它?
在这种情况下,声明属性的顺序似乎很重要,因为设置Command属性会导致CanExecute在CommandParameter设置之前立即触发。
尝试将CommandParameter属性移到Command属性之前:
另请参见here和here。
编辑
若要确保正确引发事件,应在
PersonModelProp
值更改时引发CanExecuteChanged事件。命令:
视图模型:
4nkexdtk2#
答案有两点:
首先,正如@akton提到的,你只能绑定到 public properties。它不一定是DependencyProperty**。
第二,我花了一些托姆才弄明白,您必须在Command属性之前设置CommandParameter的绑定。即
希望这有帮助:)
vatpfxk53#
_PersonModel
是私有的,因此无法访问。创建一个公开它的公共属性并绑定到CommandParameter
中的公共属性。请记住,将属性设置为依赖属性(技术上不是必需的,但它有帮助),ViewModel应该实现INotifyProperty changed并触发PropertyChanged事件,以便更新绑定。4urapxun4#
我想你的EditPersonCommand有问题(它没有被激活)。我用relayCommand检查它,它工作了!
这就是代码:
视图模型:
而这个RelayCommand(Fire events ok!)
Xmal:
zphenhs45#
命令参数必须允许null