如何在Silverlight中降低DataGridCell的高度?

时间:2011-08-16 14:45:47

标签: silverlight datagrid

Silverlight DataGrid中文本行的上方和下方有“很多”空格。

DataGridCell生成的默认DataGridTextColumn实例呈现TextBlock,其中保证金为4(使用Silverlight Spy计算出来)。

我尝试创建自定义DataGridCell模板,并将边距填充值设置为零,但这既不设置也不设置{{1}改变了什么。

您是否知道如何将某些ContentTemplate的高度降低到0旁边的值?

提前致谢!

1 个答案:

答案 0 :(得分:1)

我自己找到了答案:

问题是DataGridTextColumn类的一部分,其中放置了每个单元格内的TextBlock:

 protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        TextBlock block = new TextBlock {
            Margin = new Thickness(4.0),
            VerticalAlignment = VerticalAlignment.Center
        };
        if (DependencyProperty.UnsetValue != base.ReadLocalValue(FontFamilyProperty))
        {
            block.FontFamily = this.FontFamily;
        }
        if (this._fontSize.HasValue)
        {
            block.FontSize = this._fontSize.Value;
        }
        if (this._fontStyle.HasValue)
        {
            block.FontStyle = this._fontStyle.Value;
        }
        if (this._fontWeight.HasValue)
        {
            block.FontWeight = this._fontWeight.Value;
        }
        if (this._foreground != null)
        {
            block.Foreground = this._foreground;
        }
        if ((this.Binding != null) || !DesignerProperties.IsInDesignTool)
        {
            block.SetBinding(TextBlock.TextProperty, this.Binding);
        }
        return block;
    }

如您所见,保证金静态设置为4.0。为了解决这个问题,我创建了一个派生类,它派生自DataGridTextColumn

public class DataGridCustomTextColumn : DataGridTextColumn
    {
        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            //Get the parent TextBlock
            TextBlock block = (TextBlock)base.GenerateElement(cell, dataItem);

            if (ElementStyle != null) //if an element style is given
            {
                //Apply each setter of the style to the generated block
                ElementStyle.Setters.OfType<System.Windows.Setter>()
                    .ForEach((setter) => block.SetValue(setter.Property, setter.Value));
            }
            //Return styled block
            return (FrameworkElement)objBlock;
        }
    }