Dav*_*vid 58 wpf datagrid styling
简单的问题:如何在WPF中的dataGridCell上设置填充?(一次一个或所有细胞,我不在乎)
我已尝试通过在DataGrid.CellStyle属性上添加setter DataGridCell.Padding以及以DataGridColumn.CellStyle相同方式使用属性而无效来使用该属性.
我也尝试使用该DataGridColumn.ElementStyle物业,没有更多的运气.
我有点卡在那里,有没有人设法在dataGridCell上应用填充?
注意:我会补充说不,我不能使用透明边框来执行此操作,因为我已经将边框属性用于其他内容.我也不能使用margin属性(看起来工作得足够令人惊讶),因为我使用了background属性,我不希望我的单元格之间有任何"空白"空间.
Fre*_*lad 116
问题是,Padding不会转移到Border模板中的那个DataGridCell.您可以编辑模板并添加TemplateBindingPadding
<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>
Run Code Online (Sandbox Code Playgroud)
Sco*_*key 20
这是一种更清洁的方法(我的观点),结合了David的方法
<Resources>
<Style x:Key="ColumnElementStyle" TargetType="TextBlock">
<Setter Property="Margin" Value="5,0,10,0" />
</Style>
</Resources>
Run Code Online (Sandbox Code Playgroud)
然后...
<DataGridTextColumn ElementStyle="{StaticResource ColumnElementStyle}" />
<DataGridTextColumn ElementStyle="{StaticResource ColumnElementStyle}" />
Run Code Online (Sandbox Code Playgroud)
(在我的情况下,我的行是只读的,所以没有EditingStyle)
差不多5年后,因为这个问题似乎仍然有用(它仍然得到了提升)并且因为它已被请求,这里是我在TextColumn上使用的解决方案(使用ElementStyle)(但是你可以做同样的事情)任何类型的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)));
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果你想直接在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>
Run Code Online (Sandbox Code Playgroud)