【问题标题】:WPF Datagrid not showing data correctly but shows correctly when columnheader clickedWPF Datagrid 未正确显示数据,但在单击列标题时正确显示
【发布时间】:2012-06-26 15:59:20
【问题描述】:

我的 wpf 应用中有 DataGrid

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

我将其ItemSource 提供为

datagrid2.ItemSource = mydatatable.DefaultView;

和它的行头为

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

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

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

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

【问题讨论】:

  • 你能贴一张你的DataGrid的图片(在无头状态下)吗?很难想象到底出了什么问题。并点击哪个ColumnHeader 解决了问题?
  • @akjoshi:点击​​任何列标题会正确地重新对齐它们。

标签: c# .net wpf wpfdatagrid


【解决方案1】:

好的,我想我知道为什么会这样了。

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

单击列标题后,它会重新计算 RowHeader 宽度,这一次是正确的,因为您的行标题有数据。

应该有一些简单的解决方案,但一种方法是像这样将RowHeaderWidthSelectAllButton(in 0,0, cell) 绑定-

// 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 个单元格数据更改第一列的宽度,它工作正常;希望这对你有用。

【讨论】:

  • 什么是HandleMatrixDataGridLayoutUpdated
  • 哦,抱歉,这是拼写错误;这是 dataGrid 的 LayoutUpdated 事件的事件处理程序。在我继承 DataGrid 以在我的情况下创建自定义 DataGridControl 时,所有这些混乱。更新答案以适合您的情况。
猜你喜欢
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 2019-05-22
  • 2018-11-01
  • 2015-04-20
  • 2011-10-02
  • 1970-01-01
相关资源
最近更新 更多