17,740
社区成员
发帖
与我相关
我的任务
分享
[code=csharp]
[/code]供一些常用的类,你完全可以按自己需要来用的.
你这个需求只需要写一个实现了ICommand接口的类,然后实例化一个对象放到你的自定义类里面,然后给他指定对应的执行方法,前台xmal绑定就行了.
例如:
public class SimpleCommand : ICommand
{
/// <summary>
/// Gets or sets the Predicate to execute when the CanExecute of the command gets called
/// </summary>
public Predicate<object> CanExecuteDelegate { get; set; }
/// <summary>
/// Gets or sets the action to be called when the Execute method of the command gets called
/// </summary>
public Action<object> ExecuteDelegate { get; set; }
public SimpleCommand(Predicate<object> canExecuteDelegate, Action<object> executeDelegate)
{
CanExecuteDelegate = canExecuteDelegate;
ExecuteDelegate = executeDelegate;
}
public SimpleCommand(Action<object> executeDelegate)
{
ExecuteDelegate = executeDelegate;
}
#region ICommand Members
/// <summary>
/// Checks if the command Execute method can run
/// </summary>
/// <param name="parameter">THe command parameter to be passed</param>
/// <returns>Returns true if the command can execute. By default true is returned so that if the user of SimpleCommand does not specify a CanExecuteCommand delegate the command still executes.</returns>
public bool CanExecute(object parameter)
{
if (CanExecuteDelegate != null)
return CanExecuteDelegate(parameter);
return true;// if there is no can execute default to true
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Executes the actual command
/// </summary>
/// <param name="parameter">THe command parameter to be passed</param>
public void Execute(object parameter)
{
if (ExecuteDelegate != null)
ExecuteDelegate(parameter);
}
#endregion
}
在你的自定义类中:
public SimpleCommand MyCommand { get; set; }=new SimpleCommand(MyFunction);
public void MyFunction(Object obj){
//你要执行的代码
}
前台xaml绑定好DataContext后(就是你的自定义类实例),你的按钮就可以绑定这个命令了:
<Button Command="{Binding MyCommand}" Content="按钮"/>