使用 MVVM 将 CommandParameter 传递给 Silverlight 中的命令
我刚刚学习 Silverlight,正在研究 MVVM 和 Commanding。
好的,我已经看到了基本的 RelayCommand 实现:
public class RelayCommand : ICommand
{
private readonly Action _handler;
private bool _isEnabled;
public RelayCommand(Action handler)
{
_handler = handler;
}
public bool IsEnabled
{
get { return _isEnabled; }
set
{
if (value != _isEnabled)
{
_isEnabled = value;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
public bool CanExecute(object parameter)
{
return IsEnabled;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler();
}
}
如何使用它通过命令传递参数?
我发现您可以像这样传递 CommandParameter
:
<Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeCommandParameter}" ... />
在我的 ViewModel 中,我需要创建命令,但 RelayCommand
需要一个 Action
> 代表。我可以使用 Action
实现 RelayCommand
- 如果可以,我该怎么做以及如何使用它?
谁能给我任何有关使用 MVVM 的 CommandParameters 的实际示例,这些示例不涉及使用第 3 方库(例如 MVVM Light),因为我想在使用现有库之前充分理解它。
谢谢。
I'm just learning Silverlight and looking at MVVM and Commanding.
Ok, so I have seen the basic RelayCommand implementation:
public class RelayCommand : ICommand
{
private readonly Action _handler;
private bool _isEnabled;
public RelayCommand(Action handler)
{
_handler = handler;
}
public bool IsEnabled
{
get { return _isEnabled; }
set
{
if (value != _isEnabled)
{
_isEnabled = value;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
public bool CanExecute(object parameter)
{
return IsEnabled;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler();
}
}
How can I pass a parameter down with a Command using this?
I've seen that you can pass a CommandParameter
like this:
<Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeCommandParameter}" ... />
In my ViewModel, I need to create the Command, but RelayCommand
is expecting an Action
delegate. Can I implement RelayCommand<T>
using Action<T>
- if so, how do I do it and how to I use it?
Can anyone give me any practical examples on CommandParameters with MVVM that don't involve using 3rd-party libraries (e.g. MVVM Light) as I want to understand it fully before using existing libraries.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是命令的基类
,这是 ViewModel 中的命令属性:
在 XAML 中设置绑定到命令属性,如下所示:
Is the Base Class for Commands
And this is your Command Property in ViewModel:
in XAML set Binding to Command Property like: