ICommand 未在 WPF 应用程序中执行

ICommand is not executed in WPF application

我有一个带有按钮的 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 class:

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 class:

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();
        }
    }
}

在您的视图模型中,将 internal ICommand MessageCommand 更改为 public ICommand MessageCommand,它将起作用。绑定到内部属性将不起作用,因为绑定由位于单独程序集中的绑定引擎解析 (PresentationFramework.dll)