我有一个简单的按钮,在执行时使用命令,这一切都正常,但我想在单击按钮时传递一个文本参数.
我认为我的XAML没问题,但我不确定如何编辑我的RelayCommand类来接收参数:
<Button x:Name="AddCommand" Content="Add"
Command="{Binding AddPhoneCommand}"
CommandParameter="{Binding Text, ElementName=txtAddPhone}" />
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
改变Action以Action<T>使得它需要一个参数(可能只是Action<object>最容易).
private readonly Action<object> _handler;
Run Code Online (Sandbox Code Playgroud)
然后简单地传递参数:
public void Execute(object parameter)
{
_handler(parameter);
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做
public ICommand AddPhoneCommand
{
get
{
return new Command<string>((x) =>
{
if(x != null) { AddPhone(x); }
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当然有你的AddPhone:
public void AddPhone(string x)
{
//handle x
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26856 次 |
| 最近记录: |