首页 > 解决方案 > WPF:实现 MVVM 按钮命令

问题描述

所以我有WPF主windoes和2的应用程序UserControls

  1. HomeView.xaml
  2. OptionsView.xaml

查看模型

public class ApplicationViewModel : INotifyPropertyChanged
    {
        #region Fields

        private ICommand changePageCommand;
        private ICommand addFilesCommand;
        private IPageViewModel _currentPageViewModel;
        private List<IPageViewModel> _pageViewModels;
        #endregion

        public ApplicationViewModel()
        {
            // Add available pages
            PageViewModels.Add(new HomeViewModel() { IsSelected = true });
            PageViewModels.Add(new OptionsViewModel() { IsSelected = false });

            // Set starting page
            CurrentPageViewModel = PageViewModels[0];
        }

        #region Properties / Commands

        public ICommand ChangePageCommand
        {
            get
            {
                if (changePageCommand == null)
                {
                    changePageCommand = new RelayCommand(
                        p => ChangeViewModel((IPageViewModel)p),
                        p => p is IPageViewModel);
                }

                return changePageCommand;
            }
        }


        public List<IPageViewModel> PageViewModels
        {
            get
            {
                if (_pageViewModels == null)
                    _pageViewModels = new List<IPageViewModel>();
                return _pageViewModels;
            }
        }

        public IPageViewModel CurrentPageViewModel
        {
            get
            {
                return _currentPageViewModel;
            }
            set
            {
                if (_currentPageViewModel != value)
                {
                    _currentPageViewModel = value;
                    OnPropertyChanged("CurrentPageViewModel");
                }
            }
        }

        #endregion

        #region Methods

        private void ChangeViewModel(IPageViewModel viewModel)
        {
            if (!PageViewModels.Contains(viewModel))
                PageViewModels.Add(viewModel);
            CurrentPageViewModel = PageViewModels.FirstOrDefault(vm => vm == viewModel);
        }

        #endregion
    }

当应用程序开始

public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow app = new MainWindow();
            ApplicationViewModel context = new ApplicationViewModel();
            app.DataContext = context;
            app.Show();
        }
    }

视窗资源

<Window.Resources>
        <DataTemplate DataType="{x:Type home:HomeViewModel}">
            <home:HomeView />
        </DataTemplate>
        <DataTemplate DataType="{x:Type options:OptionsViewModel}">
            <options:OptionsView />
        </DataTemplate>
    </Window.Resources>

在里面HomeView.xaml我有简单的button

<Button Command="{Binding DataContext.AddFilesCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
        CommandParameter="{Binding}"/>

我想添加简单的Click命令,一些东西。

所以我尝试添加这个ICommand

public ICommand AddFilesCommand
{

}

有什么建议如何在每个之后执行的命令上添加这种类型Button Click

标签: wpfmvvm

解决方案


这可以更容易地完成。我会创建一个类来轻松实现命令:

using System;
using System.Windows.Input;

namespace YourNameSpace
{
    public class RelayCommand : ICommand
    {
        private Action Action;

        public Command(Action _action)
        {
            Action = _action;
        }

        public event EventHandler CanExecuteChanged = (sender, e) => { };

        public bool CanExecute(object parameter) => true;

        public void Execute(object parameter)
        {
            Action();
        }
    }
}

然后创建命令(你不需要私有 ICommand ):

public ICommand AddFileCommand { get; set; }

并像这样使用它(在构造函数中):

AddFileCommand = new RelayCommand(()=> 
{
    MethodToExecute();
});

XAML:

<Button Command="{Binding AddFileCommand}"/>

这样,您的代码将更容易看到低谷。


推荐阅读