当我在WPF中的DataGrid中选择一行时,如何勾选CheckBoxColumn

时间:2017-08-03 12:37:31

标签: c# wpf datagrid

我的DataGrid列出了保存在数据库中的联系人:

<DataGrid ItemsSource="{Binding ContactsView}"
            Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"
            x:Name="contactsDataGrid" AutoGenerateColumns="False"
            EnableRowVirtualization="True" Padding="10"
            CanUserAddRows="False"
            RowDetailsVisibilityMode="VisibleWhenSelected"
            SelectionChanged="contactsDataGrid_SelectionChanged">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Select" Width="50" />
        <DataGridTextColumn Binding="{Binding Salutation}" Header="Salut." />
        <DataGridTextColumn Binding="{Binding FirstName}" Header="First Name" />
        <DataGridTextColumn Binding="{Binding LastName}" Header="Last Name" />
        <DataGridTextColumn Binding="{Binding EmailAddress}" Header="Email Address" />
        <DataGridTextColumn Binding="{Binding Mobile}" Header="Mobile Number" />
        <DataGridTextColumn Binding="{Binding BroadDesignation}" Header="Broad Designation" />
        <DataGridTextColumn Binding="{Binding Designation}" Header="Designation" />
    </DataGrid.Columns>
</DataGrid>

用户应通过单击选择一行。进行选择后,联系人将被添加到稍后使用的另一个列表中:

private List<Contact> SelectedContacts = new List<Contact>();
private void contactsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid ThisGrid = (DataGrid)sender;            
    Contact SelectedContact = (Contact)ThisGrid.SelectedItem;

    if (!SelectedContacts.Contains(SelectedContact))
        SelectedContacts.Add(SelectedContact);
}

如何做到这一点,以便当用户做出选择时,CheckBoxColumn会更改为选中复选框的状态,以便用户知道他们已经选择了该行?

1 个答案:

答案 0 :(得分:0)

我会在您的类中添加另一个名为IsSelected的属性。在SelectionChanged方法中,您只需将属性设置为true并刷新dataGrid。

以下内容(未经测试):

private void contactsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid ThisGrid = (DataGrid)sender;            
    Contact SelectedContact = (Contact)ThisGrid.SelectedItem;
    SelectedContact.IsSelected = true;
    contactsDataGrid.Items.Refresh();

    if (!SelectedContacts.Contains(SelectedContact))
        SelectedContacts.Add(SelectedContact);
}