简体   繁体   中英

WPF Button Command not firing, what am I missing?

I feel bad posting this because I see a ton of similar posts, but after going through them all I can't quite diagnose my issue still. What I have is a WPF app designed with the MVVM pattern and using a RelayCommand() implementation for commands.

In my user control's XAML I set the data context here :

<UserControl.DataContext>
    <viewModel:SidePanelViewModel />
</UserControl.DataContext>

Then further down in the XAML I have this snippet where I assign a button's command

<TextBlock FontWeight="Bold" Margin="0,0,0,10">Service List</TextBlock>
<ListBox MaxHeight="100"
        ItemsSource="{Binding ServiceList}"
        SelectedItem="{Binding ServiceToRemove}">
</ListBox>
<Button HorizontalAlignment="Left" Width="60" Margin="0,10"
        Command="{Binding RemoveServiceCommand}">Remove</Button>

I am binding the button to the Command RemoveApplicationCommand which I define in the SidePanelViewModel here :

public ICommand RemoveServiceCommand
{
    get { return new RelayCommand(RemoveService, CanRemoveService); }
}

private void RemoveService()
{
    ServerList.Remove(ServiceToRemove);
}

private bool CanRemoveService()
{
    return true;
}

The problem

If I debug, the getter for RemoveServiceCommand will be reached when the button starts up, but when I click the button the code doesn't reach it. I had a very similar implementation (or so I think) working before, so this is really puzzling me. How can I get the command to fire on click?

Command="{Binding RemoveApplicationCommand}"

您是说RemoveServiceCommand吗?

You're returning a new RelayCommand in your getting, but not saving / caching the instance. Save it in a member variable.

if (_cmd == null)
   _cmd = new ....

return _cmd;

Try implementing like this

   private ICommand finishCommand;

        public ICommand FinishCommand
        {
            get
            {
                if (this.finishCommand == null)
                {
                    this.finishCommand = new RelayCommand<object>(this.ExecuteFinishCommand, this.CanExecutFinishCommand);
                }

                return this.finishCommand;
            }
        }

private void ExecuteFinishCommand(object obj)
        {
}
 private bool CanExecutFinishCommand(object obj)
        {
            return true;
        }

Turns out the debugger was going over RemoveService the entire time but I had not put a breakpoint there. I had a wrong name in my RemoveService implementation ServerList.Remove() should have been ServiceList.Remove() . I assumed the debugger would hit a breakpoint in the RemoveServiceCommand property's getter but it turns out it doesn't hit that when you click the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM