ProfK
ProfK

Reputation: 51063

Why is this command not invoked?

Here is what I consider the relevant part of the ListView in question:

<ListView ItemsSource="{Binding People}" >
    <ListView.View>
        <GridView>
            <GridViewColumn>
                <GridViewColumn.HeaderTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding AllSelected}" Command="{Binding ToggleSelectAll}"  CommandParameter="{Binding}" />
                    </DataTemplate>
                </GridViewColumn.HeaderTemplate>
                </GridViewColumn.HeaderTemplate>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding IsSelected}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>

The first column is thus a checkbox bound to the IsSelected property of the row item, a PickListPerson.

The command is declared in the PersonPickListViewModel as follows:

public DelegateCommand<PersonPickListViewModel> ToggleSelectAll { get; set; } = new DelegateCommand<PersonPickListViewModel>(vm =>
    {
        vm.AllSelected = !vm.AllSelected;
        vm.People.ToList().ForEach(p => p.IsSelected = vm.AllSelected);
    },
    vm => true
);

I pass the viewmodel as the command parameter so as to have access to instance properties of the viewmodel in the static context of the command's action delegate.

Yet when I click the header column checkbox, this command is not invoked. Why could that be?

Upvotes: 0

Views: 67

Answers (1)

ibebbs
ibebbs

Reputation: 1993

The DataContext at the point you bind the CommandParamter is the item from the People collection. I'm guessing this isn't the PersonPickListViewModel you're expecting. As whatever this type is can't be cast to PersonPickListViewModel the command doesn't get invoked.

Edit after first comment: If your PersonPickListViewModel is at the root of the window, you can use "DataContext Anchoring" to get to it. Simply add a name to your Window (i.e. x:Name="view") and then update your binding to use an ElementName source as follows:

{Binding ElementName=view, Path=DataContext}

Upvotes: 2

Related Questions