Clint
Clint

Reputation: 6220

WPF ICommand not firing

I'm aware this sort of thing gets asked all the time, and yes, I've got the set-up of the command on my view model correct.

The Data Context is also correct, I've checked with Snoop and it shows the command bound and with no errors (it does have a value source of unknown if that's useful...).

Here's a stupid example of code I have:

public class UserManagementViewModel : NotificationObject
{
    private RelayCommand _removeUserCommand;
    private AutoDelegateCommand _addUserCommand;

    public UserManagementViewModel(IEnumerable<UserInfo> users)
    {

    }

    public ICommand AddUserCommand
    {
        get { return _addUserCommand = _addUserCommand ?? new AutoDelegateCommand(DoAddUser); }
    }

    private void DoAddUser()
    {

    }

    public ICommand RemoveUserCommand
    {
        get { return _removeUserCommand = _removeUserCommand ?? new RelayCommand(DoRemoveUser); }
    }

    private void DoRemoveUser()
    {

    }
}

I've tried both RelayCommand from this gist: https://gist.github.com/flq/833551 and AutoDelegateCommand which is basically the same thing, but from Prism.

The command is binding, but when I then click the button, the method isn't invoked!

Any ideas?

XAML

<TabControl>
    <TabItem Header="Users">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="10*" />
                <ColumnDefinition Width="23*" />
            </Grid.ColumnDefinitions>

            <GroupBox Grid.Column="0" Margin="5" Header="Users">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <StackPanel Orientation="Horizontal" Grid.Row="0"
                            HorizontalAlignment="Right" VerticalAlignment="Top">
                        <Button Content="-" CommandParameter="{Binding RemoveUserCommand}" Margin="3" />
                        <Button Content="+" CommandParameter="{Binding AddUserCommand}" Margin="3" />
                    </StackPanel>

                    <ListBox Grid.Row="1" Margin="0,3,0,0"
                             ItemsSource="{Binding Users}"
                             SelectionMode="Single"
                             SelectedItem="{Binding SelectedUser}">

                    </ListBox>
                </Grid>
            </GroupBox>
        </Grid>
    </TabItem>
    <TabItem Header="Groups">

    </TabItem>
</TabControl>

This TabControl is just in a containing UserControl with no DataContext set on it or anything funky.

Upvotes: 1

Views: 995

Answers (1)

dkozl
dkozl

Reputation: 33364

You're binding CommandParameter insted of Command

<Button Content="-" Command="{Binding RemoveUserCommand}" Margin="3" />
<Button Content="+" Command="{Binding AddUserCommand}" Margin="3" />

Upvotes: 3

Related Questions