Datagrid (WPF) 以编程方式设置列样式(不是 xaml)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17911159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:18:26  来源:igfitidea点击:

Datagrid (WPF) Column styling programmatically (not xaml)

wpfdatagridwpfdatagriddatagridtemplatecolumn

提问by ssarangi

I have looked on SO but haven't found an exact answer to what I am looking for. I have a DataGrid view bound to a data source. I want to style columns programmatically after the window with the datagrid is visible. I also want to change it from time to time based on some behavior.

我已经看过了,但还没有找到我正在寻找的确切答案。我有一个绑定到数据源的 DataGrid 视图。我想在带有数据网格的窗口可见后以编程方式设置列的样式。我也想根据一些行为不时改变它。

I tried to use the DataGridTemplateColumn but whenever it runs it deletes the data from those columns. Also I don't get the Cell Style when I try to get it from Resources (i.e. its always null)

我尝试使用 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 is like this

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>

Any help on this would be appreciated. thanks

对此的任何帮助将不胜感激。谢谢

回答by Anatoliy Nikolaev

Here's an example of adding a column with Style:

这是添加列的示例Style

XAML

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

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();
}

Most likely, you do not pointed Bindingfor the new column.

很可能,您没有指向Binding新列。

Alternatively, set the Stylefor an existing column:

或者,Style为现有列设置 :

Specify the name of the column:

指定列的名称:

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

Set the Stylein code:

设置输入Style代码:

MySuperColumn.CellStyle = style;