WPF CommandParameter RelativeSource Binding

懵懂的女人 提交于 2019-12-13 12:49:25

问题


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>

回答1:


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



来源:https://stackoverflow.com/questions/56435313/wpf-commandparameter-relativesource-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!