wpf中窗口的按钮响应函数如何关联到自定义的类中

joyoyang 2020-12-03 01:52:21
就是说我的按钮响应函数(OnButtonXXX)不想直接放在窗口XAML的后台代码中,而是想绑定到一个我自定义的类中,这个怎么实现?我不想借助MVVM框架啥的,就是单纯用WPF怎么实现?

注:就是如何解耦这个按钮的响应逻辑函数和窗口类之间的耦合(我的窗口后台类不想写任何代码)。
...全文
2438 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
独立观察员 2020-12-04
  • 打赏
  • 举报
回复
ziqi0716 2020-12-04
  • 打赏
  • 举报
回复
MVVM框架仅仅是帮你实现了常用的一些接口,提
[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="按钮"/>
gs0038 2020-12-03
  • 打赏
  • 举报
回复
把你的类做自定义按扭类,就是继承原按按扭类 然后事件在自定义按扭写就行了 ,窗口拖自定义按扭过来,直接用就行了

17,740

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧