Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create DataGrid column separator

Is there a way to create a visual separator between two particular columns in a DataGrid? It doesn't need to be fancy, maybe just a double line or a thicker border.

like image 354
shader Avatar asked Jul 26 '11 13:07

shader


1 Answers

In case it's something like this

enter image description here

You can achieve using a custom style:

<Window.Resources>
    <Style x:Key="DataGridColumnSeparatorStyle" TargetType="DataGridCell">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Fill="Gray"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<DataGrid x:Name="dataGrid" AutoGenerateColumns="False">        
    <DataGrid.Columns>
        <DataGridTextColumn Header="Start"/>
        <DataGridTextColumn Header="End"/>
        <!-- Separator column -->
        <DataGridTemplateColumn MinWidth="0" Width="2" CellStyle="{StaticResource DataGridColumnSeparatorStyle}"/>
        <DataGridTextColumn Header="Start"/>
        <DataGridTextColumn Header="End"/>
    </DataGrid.Columns>
</DataGrid>

If you generate the columns in code-behind, either by autogenerate columns or other, you can still create the separator column by getting the resource from the XAML:

DataGridTextColumn s1 = new DataGridTextColumn() { Header = "Start" };
DataGridTextColumn s2 = new DataGridTextColumn() { Header = "Start" };
DataGridTextColumn e1 = new DataGridTextColumn() { Header = "End" };
DataGridTextColumn e2 = new DataGridTextColumn() { Header = "End" };

DataGridTemplateColumn column = new DataGridTemplateColumn();
column.MinWidth = 0;
column.Width = 2;

var separatorStyle = (Style)FindResource("DataGridColumnSeparatorStyle");
column.CellStyle = separatorStyle;

dataGrid.Columns.Add(s1);
dataGrid.Columns.Add(e1);
dataGrid.Columns.Add(column);
dataGrid.Columns.Add(s2);
dataGrid.Columns.Add(e2);
like image 80
sondergard Avatar answered Oct 03 '22 16:10

sondergard