Home > Mobile >  WPF - command binding not being called
WPF - command binding not being called

Time:04-11

I have a close button which is binding to a close command defined in my main viewmodel but for some reason it's not firing:

Button in mainview.xaml:

<Button Grid.Row="0" Style="{DynamicResource MyButtonStyle}" Margin="270,3,10,7"
                    Command="{Binding CloseCommand}"/>

Command declaration in MainViewModel:

 public class MainViewModel : BaseViewModel
    {

        public ICommand CloseCommand { get; set; }

    }

Command definition in CloseCommand.cs:

public class CloseCommand : ICommand
{
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        System.Windows.Application.Current.Shutdown();
    }
}

I set a breakpoint at CloseCommand but it isn't even getting there, what gives?

CodePudding user response:

I think that Sir Rufo is pointing out your problem. But I'd like to recommend you to take a look at the Community Toolkit MVVM. Its source generator will help you with your MVVM related code.

For example, your ViewModel...

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace WpfCloseCommandSample;

[ObservableObject]
// This class needs to be "partial" for the source generator.
public partial class MainWindowViewModel
{
    [ObservableProperty]
    // The source generator will create a
    // "ButtonName" property for you.
    private string _buttonName;

    [ICommand]
    // The source generator will create a
    // "CloseCommand" command for you.
    private void Close()
    {
        System.Windows.Application.Current.Shutdown();
    }

    // Constructor
    public MainWindowViewModel()
    {
        this.ButtonName = "Click here to close the window";
    }
}

And your XAML...

<Window
    x:Class="WpfCloseCommandSample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfCloseCommandSample"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <Button Command="{Binding CloseCommand}" Content="{Binding ButtonName}" />
    </Grid>
</Window>
  • Related