栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将WPF按钮绑定到ViewModelBase中的命令?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将WPF按钮绑定到ViewModelBase中的命令?

 <Grid >    <Grid.ColumnDefinitions>        <ColumnDefinition Width="*"/>    </Grid.ColumnDefinitions>    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/></Grid>

窗口后面的代码:

public partial class MainWindow : Window{    public MainWindow()    {        InitializeComponent();        DataContext = new ViewModelbase();    }}

ViewModel:

public class ViewModelbase{    private ICommand _clickCommand;    public ICommand ClickCommand    {        get        { return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));        }    }     public bool CanExecute     {        get        { // check if executing is allowed, i.e., validate, check if a process is running, etc.  return true/false;        }     }    public void MyAction()    {    }}

命令处理程序:

 public class CommandHandler : ICommand{    private Action _action;    private Func<bool> _canExecute;    /// <summary>    /// Creates instance of the command handler    /// </summary>    /// <param name="action">Action to be executed by the command</param>    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>    public CommandHandler(Action action, Func<bool> canExecute)    {        _action = action;        _canExecute = canExecute;    }    /// <summary>    /// Wires CanExecuteChanged event     /// </summary>    public event EventHandler CanExecuteChanged    {        add { CommandManager.RequerySuggested += value; }        remove { CommandManager.RequerySuggested -= value; }    }    /// <summary>    /// Forcess checking if execute is allowed    /// </summary>    /// <param name="parameter"></param>    /// <returns></returns>    public bool CanExecute(object parameter)    {        return _canExecute.Invoke();    }    public void Execute(object parameter)    {        _action();    }}

我希望这会给你这个主意。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568535.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号