2012-06-25 31 views
3

我在我的WPF应用程序WPF Datagrid中显示不正确的数据,但正确地显示时的columnHeader点击

<DataGrid Name="datagrid2" ItemSource="{Binding}" CanUserReorderColumns="False" 
      IsReadOnly="True" SelectionMode="Single" CanUserResizeColumns="False" 
      CanUserResizeRows="False" LoadingRow="datagrid2_LoadingRow" /> 

DataGrid,我提供了ItemSource

datagrid2.ItemSource = mydatatable.DefaultView; 

及其作为

的rowHeader
private void datagrid2_LoadingRow(object sender, DataGridRowEventArgs e) 
{ 
    e.Row.Header = Some_string_araay[e.Row.GetIndex()]; 
} 

有时我的问题出现,rowheader变成第一列的数据。因此最后一列及其数据变为无头。我认为这是一个布局问题,所以在提供ItemSourceLoadingRow后,我做了datagrid2.UpdateLayout()。但问题依然如故。

enter image description here

enter image description here

当我点击任何ColumnHeader,数据被正确对齐。

enter image description here

enter image description here

可能是什么这个问题的原因和解决办法?

+0

你可以发布你的DataGrid的图像(无haeaderless状态)?很难想象究竟发生了什么问题。并点击哪个'ColumnHeader'解决了这个问题? – akjoshi

+0

@akjoshi:点击​​任何columnheader可以正确地重新排列它们。 –

回答

2

好吧,我想我知道为什么会发生这种情况。

当网格加载时,第一列(具有行标题)的宽度根据其内容(行标题数据)在运行时确定。现在你的情况,当网格加载你的行标题没有数据(你在LoadingRow事件中设置标题),所以第一列的宽度设置为0;一旦更新行标题,它将不会被反映,因为DataGrid不会自行刷新。

一旦你点击一个列标题,它将重新计算RowHeader宽度,这次它是正确的,因为你的行标题有数据。

应该有一些简单的解决办法这一点,但一个办法做到这一点可以绑定你的RowHeaderWidthSelectAllButton(在0,0,细胞)像这样 -

// Loaded event handler for Datagrid 
private void DataGridLoaded(object sender, RoutedEventArgs e) 
{ 
    datagrid2.LayoutUpdated += DataGridLayoutUpdated; 
} 

private void DataGridLayoutUpdated(object sender, EventArgs e) 
{ 
    // Find the selectAll button present in grid 
    DependencyObject dep = sender as DependencyObject; 

    // Navigate down the visual tree to the button 
    while (!(dep is Button)) 
    { 
     dep = VisualTreeHelper.GetChild(dep, 0); 
    } 

    Button selectAllButton = dep as Button; 

    // Create & attach a RowHeaderWidth binding to selectAllButton; 
    // used for resizing the first(header) column 
    Binding keyBinding = new Binding("RowHeaderWidth"); 
    keyBinding.Source = datagrid2; 
    keyBinding.Mode = BindingMode.OneWay; // Try TwoWay if OneWay doesn't work) 
    selectAllButton.SetBinding(WidthProperty, keyBinding); 

    // We don't need to do it again, Remove the handler 
    datagrid2.LayoutUpdated -= DataGridLayoutUpdated; 
} 

我已经做了类似的东西根据第0,0个单元格数据更改第一列的widht,它工作正常;希望这会对你有用。

+0

什么是HandleMatrixDataGridLayoutUpdated? –

+0

哦,对不起,这是错误的错误;这是dataGrid的LayoutUpdated事件的事件处理程序。所有这些融合,因为我继承了DataGrid来创建自定义的DataGridControl。更新答案以适应您的情况。 – akjoshi