wpf - 我可以让 DataGrid 样式的 Content Presenter 因列而异吗?
问题描述
我继承了以下样式:
<Style x:Key="MainPlanDataGridCell" TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Height" Value="30" />
<Setter Property="FrameworkElement.HorizontalAlignment" Value="Stretch" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
...
</Style>
<Style x:Key="MainPlanTable" TargetType="{x:Type DataGrid}">
...
<Setter Property="CellStyle" Value="{StaticResource MainPlanDataGridCell}" />
...
</Style>
它在控件中使用如下:
<DataGrid
Grid.Row="2"
Grid.Column="0"
...
Style="{StaticResource MainPlanTable}">
<DataGrid.Columns>
...
</DataGrid.Columns>
</DataGrid>
但我需要不同的单元格列有不同的对齐方式。有没有办法使用样式来实现这一点?如果没有,有人可以提出实现这一目标的最佳方法(高级方法)吗?
解决方案
我为原型应用程序创建了类似的东西,如果可能的话,您可以提取样式。否则就这样使用它,
<DatGrid.Columns>
<DataGridTemplateColumn Header="ColumnHeader1" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding something}" //your alignment & other styles here />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="ColumnHeader2" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding somethingElse}" //your alignment & other styles here />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
...
</DataGrid.Columns>
您可以控制单元格是 TexBlock 还是 TextBox 或任何其他控件。也许为每个文本框/文本块制作一个样式并将其作为静态资源放在该 xaml 标记中。
注意:如果这样做,您需要设置<DataGrid AutoGenerateColumns="False">
推荐阅读
- php - Woocommerce - 在初始化和注册按钮点击后加载 Jquery 函数
- java - Springboot OAuth2授权服务器刷新令牌未在数据库中创建
- arrays - 仅按行随机播放二维数组
- c++ - 如果我将迭代器存储在某处,是否可以在 O(1) 中从 std::list 插入/删除元素。迭代器是一种指针。对吧?
- c# - 无法从 BsonType 'Array' 异常中反序列化 'BsonDocument'
- sql-server - Django 无法使用多个主键修改 SQL Server 中的一行
- python - 在文件目录中搜索关键字
- android - 如何在 Fragments 中设置 RecyclerView OnClickListener 和 OnLongClickListener?
- sql-server - 使用 Date >= 搜索记录
- mongodb - MongoDB Config 服务器复制设置失败 - 分布式锁 pinger ping 失败