Search code examples
c#wpfbindingicommand

ICommand is not executed in WPF application


I have a WPF application with a button which I bind to MessageCommand. In order to make it simple, the app only has a button which should display a messagebox. However, when I click the button, nothing happens. I am following the instructions of CodeProject but I do not know what I am missing despite the wealth of questions and answers about this topic.

The XAML file:

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

The 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!");
        }
    }
}

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


Solution

  • In your view model, change internal ICommand MessageCommand to public ICommand MessageCommand and it will work. Binding to internal properties won't work because binding is resolved by a binding engine which is in a separate assembly (PresentationFramework.dll)