使用编程方式(而非XAML)对DataGrid(WPF)列进行样式设置。

3

我在SO上查找,但没有找到我想要的确切答案。 我有一个绑定到数据源的DataGrid视图。 我想在datagrid窗口可见后通过编程方式设置列样式。 我还想根据某些行为不时更改它。

我尝试使用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)m_DataGrid.Resources["ColumnGone"]; templateColumn.CellStyle = style;。请告诉我是否有帮助。 - Anatoliy Nikolaev
非常感谢您的回答,Anatoliy。那个方法很有效。然而,我应用样式后仍然存在一个问题,即这些列中的原始数据会丢失。 - ssarangi
2个回答

2
以下是关于使用Style添加列的示例:

XAML

<Grid>
    <DataGrid x:Name="m_DataGrid" Width="400" 
                          AutoGenerateColumns="True"
                          HorizontalAlignment="Left"
                          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" />
                <Setter Property="Foreground" Value="White" />
            </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>

    <Button Name="AddColumn" Content="AddColumn" Width="100" Height="30" HorizontalAlignment="Right" Click="AddColumn_Click" />
</Grid>

Code behind

public class Person
{
    public string Sample { get; set; }
}

private ObservableCollection<Person> TestCollection = new ObservableCollection<Person>();

public MainWindow()
{
    InitializeComponent();

    TestCollection.Add(new Person() { Sample = "Orange"});
    TestCollection.Add(new Person() { Sample = "White"});
    TestCollection.Add(new Person() { Sample = "Green"});

    m_DataGrid.ItemsSource = TestCollection;
}

private void StyleColumns()
{            
    DataGridTextColumn MyColumn = new DataGridTextColumn();
    MyColumn.Header = "Test";
    MyColumn.Binding = new Binding("Sample");

    Style style = (Style)m_DataGrid.Resources["ColumnGone"];
    MyColumn.CellStyle = style;           
    m_DataGrid.Columns.Add(MyColumn);
}

private void AddColumn_Click(object sender, RoutedEventArgs e)
{
    StyleColumns();
}

很可能你没有为新列指定Binding

另一种方法是为现有的列设置Style

指定列的名称:

<DataGridTextColumn x:Name="MySuperColumn" Header="MyColumn" Binding="{Binding Path=Sample}" Width="100" />

在代码中设置Style

MySuperColumn.CellStyle = style;

0
/*****************************************************************
* Color me pink, but I found the following a straightforward method 
* to change the style of the columns in a WPF DataGrid.

* My code populated a DataTable with Crypto Exchange market Ticker 
* information. Four of the five columns had numeric data, which I 
* wanted to right align.
*****************************************************************/

DataTable dtblTickers;
...
    // Code populated five columns in dtblTickers
...

// bind the five (5) column DataTable to a WPF DataGrid already in the Form
gridTickers.DataContext = dtblTickers;

// Auto generate the DataGrid columns to fit the data
gridTickers.AutoGenerateColumns = true;

// Unfortunately, the four numeric columns are left aligned.
// Now, change the alignment of the numeric columns to be right aligned.
// This requires creation of a Setter object for Cell Style, as follows:

// Create a Style object for reuse.
Style cellStyle = new Style(typeof(DataGridCell));

// Create a Setter object to set (get it? Setter) horizontal alignment.
Setter setAlign = new
    Setter(DataGridCell.HorizontalAlignmentProperty,
    HorizontalAlignment.Right);

// Bind the Setter object above to the Style object
cellStyle.Setters.Add(setAlign);

// Bind the new Right Alignment Style object to each of the numeric columns.
gridTickers.Columns[1].CellStyle = cellStyle;
gridTickers.Columns[2].CellStyle = cellStyle;
gridTickers.Columns[3].CellStyle = cellStyle;
gridTickers.Columns[4].CellStyle = cellStyle;

// Refresh the WPF DataGrid to show the new alignment settings.
gridTickers.Items.Refresh();

// Done. The WPF DataGrid now has the four numeric columns right aligned.

请添加更多细节以扩展您的答案,例如工作代码或文档引用。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接