【发布时间】:2020-06-01 21:41:07
【问题描述】:
我有一个 WPF 应用程序,它带有一个绑定到 MessageCommand 的按钮。为了简单起见,该应用程序只有一个应该显示消息框的按钮。但是,当我单击按钮时,什么也没有发生。我遵循CodeProject 的指示,但我不知道我错过了什么,尽管关于这个主题有很多问题和答案。
XAML 文件:
<Window x:Class="CommandTestProject.MainWindow"
...
xmlns:local="clr-namespace:CommandTestProject"
xmlns:vw="clr-namespace:CommandTestProject.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<vw:ViewModelMsg/>
</Window.DataContext>
<Grid>
<Button Content="Click"
Command="{Binding Path=MessageCommand}"/>
</Grid>
</Window>
ViewModel 类:
using CommandTestProject.Commands;
using System;
using System.Windows;
using System.Windows.Input;
namespace CommandTestProject.ViewModel
{
public class ViewModelMsg
{
private ShowMessage showMsg;
public ViewModelMsg()
{
showMsg = new ShowMessage(this);
}
internal ICommand MessageCommand
{
get
{
return showMsg;
}
}
internal void Message()
{
MessageBox.Show("This is a test command!");
}
}
}
ShowMessage 类:
using CommandTestProject.ViewModel;
using System;
using System.Windows.Input;
namespace CommandTestProject.Commands
{
public class ShowMessage : ICommand
{
private ViewModelMsg viewModel;
public event EventHandler CanExecuteChanged;
public ShowMessage(ViewModelMsg vm)
{
viewModel = vm;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
viewModel.Message();
}
}
}
【问题讨论】: