【问题标题】:Setting DataGrid row height property programmatically以编程方式设置 DataGrid 行高属性
【发布时间】:2012-01-28 09:52:29
【问题描述】:

我有一个关于 .NET 4.0 中的标准 WPF DataGrid 的问题。

当我尝试使用简单代码以编程方式设置 DataGrid 网格行高时:

private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Height = 120;            
}

一切都很好,直到我尝试在用户界面上调整网格行的大小/在侧面使用鼠标像在 excel/ 中的标准方式 - 然后它似乎无法调整网格行的大小。它一直是 120。顺便说一下,它的内容都搞砸了......

就像 Sinead O'Connor 会说的:告诉我宝贝 - 我哪里做错了?

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    您不应该设置行本身的高度,因为它是通过标题等调整大小的。有一个属性,DataGrid.RowHeight,可以让您正确地执行此操作。

    如果您需要选择性地设置高度,您可以创建一个样式并将DataGridCellsPresenter 的高度绑定到您的项目的某些属性:

    <DataGrid.Resources>
        <Style TargetType="DataGridCellsPresenter">
            <Setter Property="Height" Value="{Binding RowHeight}" />
        </Style>
    </DataGrid.Resources>
    

    或者你可以从可视化树中获取演示者(我确实推荐这个)并在那里分配一个高度:

    // In LoadingRow the presenter will not be there yet.
    e.Row.Loaded += (s, _) =>
        {
            var cellsPresenter = e.Row.FindChildOfType<DataGridCellsPresenter>();
            cellsPresenter.Height = 120;
        };
    

    FindChildOfType 是一个扩展方法,可以这样定义:

    public static T FindChildOfType<T>(this DependencyObject dpo) where T : DependencyObject
    {
        int cCount = VisualTreeHelper.GetChildrenCount(dpo);
        for (int i = 0; i < cCount; i++)
        {
            var child = VisualTreeHelper.GetChild(dpo, i);
            if (child.GetType() == typeof(T))
            {
                return child as T;
            }
            else
            {
                var subChild = child.FindChildOfType<T>();
                if (subChild != null) return subChild;
            }
        }
        return null;
    }
    

    【讨论】:

      【解决方案2】:

      这对我有用。

      private void SetRowHeight(double height)
      {
          Style style = new Style();
          style.Setters.Add(new Setter(property: FrameworkElement.HeightProperty, value: height));
          this.RowStyle = style;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-08-20
        • 2017-08-05
        • 2012-01-29
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 2023-01-03
        • 2020-12-02
        相关资源
        最近更新 更多