2013-01-18 79 views
0

我有一个wpf格式的DataGrid。它有一些带有复选框的行。我想要选中/取消选中标题复选框已选中/未选中的所有行。选择/取消选择网格中的所有行

但我收到此错误: “对象引用不设置到对象的实例”上chk.IsChecked =假。

enter image description here

C#代码:

private void myDataGrid_LoadingRow(object sender, DataGridRowEventArgs e) 
    { 
     CheckBox chk = (CheckBox)this.myDataGrid.Columns[0].GetCellContent(e.Row); 
     chk.IsChecked = false; 
     checkboxes.Add(chk); 
    } 

XAML代码是:

<Window x:Class="WpfApplication1.Grid" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Grid" Height="300" Width="300"> 
<Grid> 
    <DataGrid x:Name="myDataGrid" 
       VerticalAlignment="Top" 
       Grid.Column="0" 
       AutoGenerateColumns="False" 
       LoadingRow="myDataGrid_LoadingRow" 
       Loaded="myDataGrid_Loaded"> 
     <DataGrid.Columns> 
      <DataGridTemplateColumn Width="80"> 
       <DataGridTemplateColumn.Header> 
        <CheckBox HorizontalAlignment="Center" 
           Click="chk_Click" 
           VerticalAlignment="Center" 
           Name="chckAll"> 
        </CheckBox> 
       </DataGridTemplateColumn.Header> 

       <DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <CheckBox x:Name="chk" 
            HorizontalAlignment="Center" 
            HorizontalContentAlignment="Center"></CheckBox> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellTemplate> 
      </DataGridTemplateColumn> 

      <DataGridTextColumn Header="First Name" 
           Width="100" 
           Binding="{Binding FirstName}"></DataGridTextColumn> 
      <DataGridTextColumn Header="Last Name" 
           Width="100" 
           Binding="{Binding LastName}"></DataGridTextColumn> 
     </DataGrid.Columns> 
    </DataGrid> 
</Grid> 

预先感谢。

+0

它看起来更像是你的chk变量为null(你不选择你的单选按钮)。你可以把一个断点,并检查它是否为空? – Sonhja

+0

ya chk变量为空。我真的不知道这个代码有什么问题: CheckBox chk =(CheckBox)this.myDataGrid.Columns [0] .GetCellContent(e.Row); –

+0

为了让你的DataGridRow,你应该遵循这个链接: http://stackoverflow.com/questions/1976087/wpf-datagrid-set-selected-row – Sonhja

回答

1

你可以对这个link做点什么。

对您来说应该是这样的:

DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex); 
CheckBox chk = (CheckBox)this.myDataGrid.Columns[0].GetCellContent(e.Row); 

我想,现在不尝试。

+0

+1我喜欢你回答 –

相关问题