gpt4 book ai didi

mvvm - 使用 MVVM 在 Silverlight 中将 CommandParameter 传递给 Command

转载 作者:行者123 更新时间:2023-11-30 23:54:55 26 4
gpt4 key购买 nike

我只是在学习 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代表。我可以实现 RelayCommand<T>使用 Action<T> - 如果是这样,我该怎么做以及如何使用它?

谁能给我任何关于使用 MVVM 的 CommandParameters 的实际示例,这些示例不涉及使用 3rd 方库(例如 MVVM Light),因为我想在使用现有库之前完全理解它。

谢谢。

最佳答案

public class Command : ICommand
{
public event EventHandler CanExecuteChanged;

Predicate<Object> _canExecute = null;
Action<Object> _executeAction = null;

public Command(Predicate<Object> canExecute, Action<object> executeAction)
{
_canExecute = canExecute;
_executeAction = executeAction;
}
public bool CanExecute(object parameter)
{
if (_canExecute != null)
return _canExecute(parameter);
return true;
}

public void UpdateCanExecuteState()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, new EventArgs());
}

public void Execute(object parameter)
{
if (_executeAction != null)
_executeAction(parameter);
UpdateCanExecuteState();
}
}

是命令的基类

这是您在 ViewModel 中的命令属性:
 private ICommand yourCommand; ....

public ICommand YourCommand
{
get
{
if (yourCommand == null)
{
yourCommand = new Command( //class above
p => true, // predicate to check "CanExecute" e.g. my_var != null
p => yourCommandFunction(param1, param2));
}
return yourCommand;
}
}

在 XAML 中设置绑定(bind)到命令属性,如:
 <Button Command="{Binding Path=YourCommand}" .../>

关于mvvm - 使用 MVVM 在 Silverlight 中将 CommandParameter 传递给 Command,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4483086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com