以编程方式设置DataGrid行高属性

4

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

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

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

在用户界面上使用鼠标调整网格行大小的标准方法(类似于Excel),一切都很顺利,直到我尝试调整网格行大小时 - 然后似乎无法调整网格行大小。它只保持在120。顺便说一下,它的内容都混乱了...

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

2个回答

5

不应该设置行高本身的高度,因为它会通过标题等进行调整。 有一个属性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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接