[英]Pass parameter with a command into the viewmodel
我无法将视图中的参数发送到我的viewmodel。
View.xaml :
在我看来,我有以下几点:
<TextBox
MinWidth="70"
Name="InputId"/>
<Button
Command="{Binding ButtonCommand}"
CommandParameter="{Binding ElementName=InputId}"
Content="Add"/>
View.xaml.cs :
public MyView()
{
InitializeComponent();
}
public MyView(MyViewModel viewModel) : this()
{
DataContext = viewModel;
}
MyViewModel.cs :
public class MyViewModel : BindableBase
{
public ICommand ButtonCommand { get; private set; }
public MyViewModel()
{
ButtonCommand = new DelegateCommand(ButtonClick);
}
private void ButtonClick()
{
//Read 'InputId' somehow.
//But DelegateCommand does not allow the method to contain parameters.
}
}
有什么建议,当我点击按钮到我的viewmodel时如何传递InputId
?
您需要将<object>
添加到您的委托命令,如下所示:
public ICommand ButtonCommand { get; private set; }
public MyViewModel()
{
ButtonCommand = new DelegateCommand<object>(ButtonClick);
}
private void ButtonClick(object yourParameter)
{
//Read 'InputId' somehow.
//But DelegateCommand does not allow the method to contain parameters.
}
您是否希望将文本框的文本更改为您的xaml:
CommandParameter="{Binding Text,ElementName=InputId}"
要正确实现ICommand / RelayCommand,请查看此MSDN页面。
摘要:
public class RelayCommand : ICommand
{
readonly Action<object> _execute;
readonly Func<bool> _canExecute;
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute.Invoke();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
public MyViewModel()
{
ButtonCommand = new RelayCommand(ButtonClick);
}
private void ButtonClick(object obj)
{
//obj is the object you send as parameter.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.