wpfcommandcommandparameter

WPF CommandParameter RelativeSource Binding


I have a ListView with a CheckBox inside of the ListView's DataTemple. I was shown how to make the Command work. I would like to capture the ListView SelectedItem to pass as a parameter to the Command, but I don't have it right...

<ListView x:Name="lvReferralSource" ItemsSource="{Binding ReferralObsCollection}" Style="{StaticResource TypeListViewStyle}">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <Grid Width="200">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <CheckBox x:Name="ckbReferralIsChecked" Content="{Binding Value}" IsChecked="{Binding Active}" Style="{StaticResource CheckBoxStyleBase2}"
                                                  Command="{Binding DataContext.CheckBoxIsChecked, RelativeSource={RelativeSource AncestorType=ListView}}" 
                                                  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=SelectedItem}">
                                        </CheckBox>
                                    </Grid>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>

Solution

  • Looking at the problem again I think I understood it correctly now. Here is a different approach to get the SelectedItem from the ListView Then in the CheckBox I bound the CommandParameter as below

    CommandParameter="{Binding ElementName=lvReferralSource, Path=SelectedItem}"

    The following will pass the object related to the CheckBox

    CommandParameter="{Binding}"// Full object from the ListView

    In the Command Method related to the CheckBox you can cast the parameter object to the correct type(type of the objects in the ListView ItemSource) and get the value of Value and Active