【问题标题】:Bind a button to a command (Windows Phone 7.5)将按钮绑定到命令 (Windows Phone 7.5)
【发布时间】:2012-08-30 19:30:01
【问题描述】:

我正在开发我的 windows-phone 应用程序,它使用一些简单的数据绑定。我已经创建了一个基于 MvvM 编程方法的应用程序。我目前正在开发的应用程序也可以通过 MvvM 方法工作。因为我想让我的代码尽可能干净,所以我一直在寻找一种方法来使“按钮单击事件”(通常发生在代码隐藏页面中)发生在我的视图模型或主视图模型中。

我已经在互联网上搜索了 Icommand 界面的简单解释,因为我相信这是要走的路。我发现的解释的问题是其中一些是基于使用 CommandRelay 函数的 MvvMlight 工具包。我不想使用 MvvM light 工具包,因为我想先了解自己。我发现的其他教程是由过于热情的开发人员编写的,它们给你的信息太多了。

有人可以告诉我绑定到按钮的 Icommand 的最简单版本吗?

【问题讨论】:

    标签: c# windows-phone-7 mvvm icommand


    【解决方案1】:

    在您的 XAML 中:

    <Button Content="My Button" Command="{Binding MyViewModelCommand}" />
    

    在您的视图模型中:

    public class MyViewModel
    {
    
        public MyViewModel()
        {
            MyViewModelCommand = new ActionCommand(DoSomething);
        }
    
        public ICommand MyViewModelCommand { get; private set; }
    
        private void DoSomething()
        {
            // no, seriously, do something here
        }
    }
    

    INotifyPropertyChanged 和其他视图模型的寒暄都省略了。
    在视图模型中构造命令的另一种方法显示在此答案的底部。

    现在,您需要实现ICommand。我建议从像这样简单的东西开始,并根据需要扩展或实现其他功能/命令:

    public class ActionCommand : ICommand
    {
        private readonly Action _action;
    
        public ActionCommand(Action action)
        {
            _action = action;
        }
    
        public void Execute(object parameter)
        {
            _action();
        }
    
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public event EventHandler CanExecuteChanged;
    }
    

    这是布局视图模型的另一种方法:

    public class MyViewModel
    {
        private ICommand _myViewModelCommand;
        public ICommand MyViewModelCommand
        {
            get 
            {
                return _myViewModelCommand
                    ?? (_myViewModelCommand = new ActionCommand(() => 
                    {
                        // your code here
                    }));
            }
        }
    }
    

    【讨论】:

    • 谢谢杰,这正是我想要的:) 平面和简单:)
    【解决方案2】:

    要添加到杰斯的答案:

    我一直最喜欢的是来自@Microsoft 模式和实践团队的 DelegateCommand。查看this post 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 2013-09-16
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 2014-05-13
      • 2015-10-26
      相关资源
      最近更新 更多