简体   繁体   中英

Toggle Checkbox in GridView on Row Click - WPF

I have this:

       <ListView Name="UserSolutionsGrid">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox HorizontalAlignment="Center" IsChecked="{Binding IsSelected}" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Width="350" DisplayMemberBinding="{Binding Name}" Header="Solution" />
                </GridView>
            </ListView.View>
        </ListView>

What I want to do is be able to toggle the checkbox by clicking the row, whether that be the checkbox itself or the Name.

Not sure how to proceed, do I need to hook up a mouse event to the gridview and find the row thats selected and then find the checkbox and toggle it?

This will do for you. What you all need to do is bind your checkBox property to IsSelected property of your ListViewItem using RelativeSource-

<ListView Name="UserSolutionsGrid">
    <ListView.View>
       <GridView>
          <GridViewColumn Header="">
              <GridViewColumn.CellTemplate>
                  <DataTemplate>
                     <CheckBox HorizontalAlignment="Center" IsChecked="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListViewItem}}" />
                   </DataTemplate>
              </GridViewColumn.CellTemplate>
          </GridViewColumn>
          <GridViewColumn Width="350" DisplayMemberBinding="{Binding Name}" Header="Solution" />
       </GridView>
     </ListView.View>
</ListView>

Since you mentioned this is multi select and that you want to be able to toggle etc I would look at using a mouse event as you initially suggested.

This would make the toggle code a bit easier. Although If you are using databinding there is no need to find the row and toggle the checkbox, just set the value of whatever your checkbox is bound to then raise OnPropertyChanged().

Is that grid view only ever going to have two columns in there? I think you could probably achieve the same result without the grid by just using an item template in the listview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM