Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c# - Freeze DataGrid Row

I was wondering if in a WPF datagrid in .net 4.0, is it possible to have a static row.

What I am trying to achieve is to create a static row (row 0), that will always be displayed at the top when the data grid is scrolled down.

The idea being that row 0 will always be in view as the user scrolls through the datagrid.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This "Simple solution" is only for a freezable footer, the frozen header solution would be a bit different (and actually much easier - just play with the HeaderTeamplate - put a stack panel with as many items stacked up as you want).

So I needed a footer row that is freezable, I couldn't find anything for months, so finally I decided to stop being lazy and investigate.

So if you need a footer, the gist is find a place in DataGrid's Template between the rows and the horizontal scrollviewer where you can squeeze extra Grid.Row with an ItemsControl with Cells.

PLAN OF ATTACK:

First, extract the DataGrid template (I used Blend). When getting familiarized with the template, note the parts in order:

 PART_ColumnHeadersPresenter
 PART_ScrollContentPresenter
 PART_VerticalScrollBar

right under PART_VerticalScrollBar, there is a grid (I'll post it here for clarity)

<Grid Grid.Column="1" Grid.Row="2">
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="{Binding NonFrozenColumnsViewportHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
      <ColumnDefinition Width="*"/>
   </Grid.ColumnDefinitions>
   <ScrollBar x:Name="PART_HorizontalScrollBar" Grid.Column="1" Maximum="{TemplateBinding ScrollableWidth}" Orientation="Horizontal" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}"/>
</Grid>

That's the grid I modified to include a "freezable/footer row". I am going to just hard-code colors, and replace Binding with hoperfully helpful "pretend" properties for simplicity (I'll mark them "MyViewModel.SomeProperty so they are easy to see):

<Grid Grid.Column="1" Grid.Row="2" x:Name="PART_DataGridColumnsVisualSpace">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=NonFrozenColumnsViewportHorizontalOffset}"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <ScrollBar Grid.Column="2" Grid.Row="3" Name="PART_HorizontalScrollBar" Orientation="Horizontal" 
           Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}"
           Value="{Binding Path=HorizontalOffset, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"
           Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/>

    <Border x:Name="PART_FooterRowHeader" Grid.Row="1" Height="30" Background="Gray" BorderBrush="Black" BorderThickness="0.5">
    <TextBlock Margin="4,0,0,0" VerticalAlignment="Center">MY FOOTER</TextBlock>
    </Border>
    <ItemsControl x:Name="PART_Footer" ItemsSource="{Binding MyViewModel.FooterRow}"
              Grid.Row="1" Grid.Column="1" Height="30">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Border Background="Gray" BorderThickness="0,0,0.5,0.5" BorderBrush="Black">
                     <!-- sticking a textblock as example, i have a much more complex control here-->
                    <TextBlock Text="{Binding FooterItemValue}"/>
                </Border>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.Template>
            <ControlTemplate>
                <ScrollViewer x:Name="PART_Footer_ScrollViewer" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" 
                          CanContentScroll="True" Focusable="false">
                    <StackPanel IsItemsHost="True" Orientation="Horizontal"/>
                </ScrollViewer>
            </ControlTemplate>
        </ItemsControl.Template>
    </ItemsControl>
</Grid>

Also add to DataGrid respond to scroll and header resize

<DataGrid ... ScrollViewer.ScrollChanged="OnDatagridScrollChanged"

<Style TargetType="DataGridColumnHeader">
    <EventSetter Event="SizeChanged" Handler="OnDataColumnSizeChanged"/>
</Style>

Now, back in .xaml.cs

Basically two main things are needed:

(1) sync column resize (so that corresponding footer cell resizes) (2) sync DataGrid scroll with footer scroll

//syncs the footer with column header resize
private void OnDatagridScrollChanged(object sender, ScrollChangedEventArgs e)
{
    if (e.HorizontalChange == 0.0) return;
    FooterScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
}

//syncs scroll
private void OnDataColumnSizeChanged(object sender, SizeChangedEventArgs e)
{
    //I don't know how many of these checks you need, skip if need to the gist
    if (!_isMouseDown) return;
    if (!_dataGridLoaded) return;
    if (!IsVisible) return;

     var header = (DataGridColumnHeader)sender;
     var index = header.DisplayIndex - ViewModel.NumberOfHeaderColumns;

     if (index < 0 || index >= FooterCells.Count) return;

     FooterCells[index].Width = e.NewSize.Width;
}

//below referencing supporting properties:
private ScrollViewer _footerScroll;
private ScrollViewer FooterScrollViewer
{
    get {
        return _footerScroll ??
              (_footerScroll = myDataGrid.FindVisualChildByName<ScrollViewer>("PART_Footer_ScrollViewer"));
        }
}

//added this so I don't have to hunt them down from XAML every time
private List<Border> _footerCells;
private List<Border> FooterCells
{
    get
    {
        if (_footerCells == null)
        {
            var ic = myDataGrid.FindVisualChildByName<ItemsControl>("PART_Footer");
            _footerCells = new List<Border>();
            for (var i = 0; i < ic.Items.Count; i++)
            {
               var container = ic.ItemContainerGenerator.ContainerFromIndex(i);                             
               var border = ((Visual)container).FindVisualChild<Border>();
              _footerCells.Add(border);
            }
         }
         return _footerCells;
    }
}

that's it! I think the most important part is the XAML to see where you can put your "freezable row", everything else, like manipulating/sync'ing things is pretty easy - almost one liners)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...