简体   繁体   中英

How to check/uncheck checkbox in WPF datagridcheckboxcolumn? And how to later retrieve the isChecked value in the code behind?

I am building an email sending application. In my window I have the following datagrid:

<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" HorizontalAlignment="Stretch" Name="dgdTo" VerticalAlignment="Stretch" ItemsSource="{Binding}" >
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="contactFName" IsReadOnly="True" Binding="{Binding Path=FirstName}" Header="First Name" Width="2*"/>
            <DataGridTextColumn x:Name="contactLName" IsReadOnly="True" Binding="{Binding Path=LastName}" Header="Last Name" Width="2*"/>
            <DataGridTextColumn x:Name="contactEmail" IsReadOnly="True" Binding="{Binding Path=Email}" Header="E-mail" Width="2*"/>
            <DataGridCheckBoxColumn x:Name="mailSend" Header="Send mail" Width="*"/>
        </DataGrid.Columns>
</DataGrid>

The first three columns are bound to ContactPerson table in database. The last column indicates whether an email should be send to the person. Since, I do not have a field 'boolean SendMail" in the ContactPerson object, I need another way for getting the value of the checkbox.

How do I get/set checkbox value for a particular row?(C#)

First, to set value to your datagrid make a DataTable (Database in Memory). In that DataTable make columns namely FirstName , LastName , Email . They all will be string type.

Add a column which should be Boolean DataType and name it Sendmail . Bind it this way Binding="{Binding Path=Sendmail}" . Now when you will give datasource of gridview, then where ever there is true in last column checkbox will get ticked and unchecked for false.

You need to introduce an intermediate object between your database and your user interface (a ViewModel ).

This could be an ObservableCollection of UIContactPerson in your case, where UIContactPerson is a copy of ContactPerson out of your database with an additional SendMail boolean property .

Then instead of binding the UI direct to the database objects, you bind to the ViewModel. Obviously you also need to hook up some way of refreshing data from the underlying data store and sending changes back.

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