WPF:实现MVVM按钮命令
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF:实现MVVM按钮命令相关的知识,希望对你有一定的参考价值。
所以我有qazxsw poi应用程序与主窗口和2 qazxsw poi:
WPF
UserControls
查看模型
HomeView.xaml
Whan申请开始
OptionsView.xaml
Windows资源
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
然后创建命令(您不需要私有ICommand):
Button Click
并像这样使用它(在构造函数中):
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();
XAML:
public ICommand AddFileCommand get; set;
这样您的代码将更容易透视。
以上是关于WPF:实现MVVM按钮命令的主要内容,如果未能解决你的问题,请参考以下文章
2019-11-29-WPF-绑定命令在-MVVM-的-CanExecute-和-Execute-在按钮点击都没触发可能的原因...