1
我曾看过,但尚未找到我正在寻找的确切答案。我有一个DataGrid视图绑定到数据源。我想在具有datagrid的窗口可见之后以编程方式对列进行样式设置。我也想根据一些行为不时地改变它。Datagrid(WPF)以编程方式创建列样式(不是xaml)
我试图使用DataGridTemplateColumn,但每当它运行它删除这些列中的数据。此外,当我尝试从资源得到它我不明白的单元格样式(即它总是空)
private void StyleColumns()
{
// Replace the DueDate column with a custom template column.
for (int i = 0; i < 7; i += 2)
{
// Create a new template column.
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = m_DataGrid.Columns[i].Header;
Style style = new Style();
templateColumn.CellStyle = (Style)Resources["ColumnGone"];
// ...
// Replace the auto-generated column with the templateColumn.
m_DataGrid.Columns[i] = templateColumn;
}
}
XAML是这样
<DataGrid AutoGenerateColumns="True" x:Name="m_grfFileDataGrid" ItemsSource="{Binding cb.GRF}"
RowHeight="20" ColumnWidth="*"
AlternatingRowBackground="Beige"
SelectionUnit="CellOrRowHeader"
FontFamily="Consolas"
FontSize="12"
CanUserReorderColumns="False"
CanUserSortColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False">
<DataGrid.Resources>
<Style TargetType="DataGridCell" x:Key="ColumnGone">
<Setter Property="Background" Value="SeaGreen"/>
</Style>
<Style x:Key="DisabledColumn">
<Setter Property="DataGridColumn.CanUserResize"
Value="False" />
<Setter Property="DataGridColumn.CanUserSort"
Value="False" />
<Setter Property="DataGridColumn.CanUserReorder"
Value="False" />
<Setter Property="DataGridColumn.CellStyle"
Value="{StaticResource ColumnGone}" />
</Style>
</DataGrid.Resources>
</DataGrid>
任何帮助,将不胜感激。感谢
尝试参照风格
另外,对于现有的列设置
Style
如下所示:'Style style =(Style)m_DataGrid.Resources [“ColumnGone”]; templateColumn.CellStyle = style;'。让我知道它是否有帮助。 –非常感谢答案阿纳托利。这工作。但是,仍然发生的一个问题是,当我应用样式时,这些列中的原始数据会丢失。 – ssarangi