Reputation: 557
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?
Upvotes: 1
Views: 9580
Reputation: 557
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.
Upvotes: 1
Reputation: 2741
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;
}
Upvotes: 1
Reputation: 7690
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;
Upvotes: 1
Reputation: 14477
Command="{Binding RemoveApplicationCommand}"
Did you mean RemoveServiceCommand
?
Upvotes: 1