在WPF中的dataGridCells上设置填充

简单的问题:如何在WPF中的dataGridCell上设置填充? (一次一个或所有单元格,我不在乎)

我已经尝试使用DataGrid.CellStyle属性,通过在DataGrid.CellStyle属性上添加一个setter以及以相同的方式使用DataGridColumn.CellStyle属性,但不起作用。

我也尝试使用DataGridColumn.ElementStyle属性,没有更多的运气。

我有点卡住了,有没有人设法得到一个数据网格应用填充?

注意:我会添加不,我不能使用透明边框来做到这一点,因为我已经使用边界属性的其他东西。 我也不能使用保证金属性(这似乎工作,令人惊讶的足够),因为我使用背景属性,我不希望我的单元格之间有任何“空白”的空间。

问题是Padding不被转移到模板DataGridCellBorder 。 您可以编辑模板并添加用于Padding的TemplateBinding

 <DataGrid ...> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="Padding" Value="20"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridCell}"> <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </DataGrid.CellStyle> <!--...--> </DataGrid> 

这是一个更清洁的方法(我的观点),结合了大卫的方法

 <Resources> <Style x:Key="ColumnElementStyle" TargetType="TextBlock"> <Setter Property="Margin" Value="5,0,10,0" /> </Style> </Resources> 

然后…

 <DataGridTextColumn ElementStyle="{StaticResource ColumnElementStyle}" /> <DataGridTextColumn ElementStyle="{StaticResource ColumnElementStyle}" /> 

(在我的例子中,我的行是只读的,所以没有EditingStyle)

大约5年后,由于这个问题似乎仍然有用(它仍然是upvv),并且因为它被请求,这里是我使用的解决scheme(与ElementStyle)在TextColumn(但你可以做同样的任何types的DataGridColumn):

我在后面的代码中完成了这一切:

 class MyTextColumn : DataGridTextColumn { public MyTextColumn() { ElementStyle = new Style(typeof(TextBlock)); EditingElementStyle = new Style(typeof(TextBox)); ElementStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(3))); EditingElementStyle.Setters.Add(new Setter(Control.PaddingProperty, new Thickness(0, 1, 0, 1))); } } 

但是如果你想直接在xaml中做:

 <DataGrid.Columns> <DataGridTextColumn> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="3"/> </Style> </DataGridTextColumn.ElementStyle> <DataGridTextColumn.EditingElementStyle> <Style TargetType="TextBox"> <Setter Property="Padding" Value="0 1 0 1"/> </Style> </DataGridTextColumn.EditingElementStyle> </DataGridTextColumn> </DataGrid.Columns> 

你也可以尝试改变

 {Binding BindingValue, StringFormat={}{0:#0.0000}} 

 {Binding BindingValue, StringFormat={}{0:#0.0000 }} 

有趣的是,WPF的XAML {0:#0.0000}将以呈现控件的格式来表示这个额外的空格字符,以便将您的值从网格列的边缘移开。

 <DataGrid.Columns> <DataGridTextColumn MinWidth="100" Header="Changed by" Width="" Binding="{Binding Changedby}" IsReadOnly="True" > <DataGridTextColumn.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Background" Value="Transparent" /> <Setter Property="FrameworkElement.HorizontalAlignment"Value="Center"/> </Style> </DataGridTextColumn.CellStyle> </DataGridTextColumn>