Reputation: 61
I have a Datagrid with Expander in it, like this:
<DataGrid ItemsSource="{Binding}" Name="MainDataGrid"
AutoGenerateColumns="False"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
SelectionMode="Extended"
CanUserDeleteRows="False"
CanUserAddRows="False"
SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
>
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander Background="#F0F7FC" BorderThickness="0" BorderBrush="BlanchedAlmond" >
<Expander.Header>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBlock Text="Text" />
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander >
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
The datagrid has a frozen column and some variable ones. When i scroll vertically, the expander header also scrolls away and disappears. Is there a way to freeze the expander heaeder,too?
DataGrid before scrolling:
DataGrid after scrolling (Expander header scrolls away):
Upvotes: 3
Views: 1920
Reputation: 61
I found a workaround:
A Simple Workaround
The simplest workaround I thought of is to adjust the left margin of the header every time the DataGrid is scrolled horizontally. To do this, we can subscribe to the ScrollChanged event of the DataGrid’s ScrollViewer, get the group header and set its margin. In our example though, we used an Expander so we need to find the ToggleButton and set its left margin. The following code listing shows the event handler for the ScrollChanged event and a recursive method that searches for the ToggleButton using the VisualTreeHelper utility class.
private void DataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
var dataGrid = (DataGrid)sender;
if (dataGrid.IsGrouping && e.HorizontalChange != 0.0)
{
TraverseVisualTree(dataGrid, e.HorizontalOffset);
}
}
private void TraverseVisualTree(DependencyObject reference, double offset)
{
var count = VisualTreeHelper.GetChildrenCount(reference);
if (count == 0)
return;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(reference, i);
if (child is ToggleButton)
{
var toggle = (ToggleButton)child;
toggle.Margin = new Thickness(offset, 0, 0, 0);
}
else
{
TraverseVisualTree(child, offset);
}
}
}
Source: http://www.nullskull.com/a/1509/freeze-row-group-header-in-wpf-datagrid.aspx
It´s not the perfect solution, but for my project it´s ok!
Upvotes: 1