0
votes

I would like to set up a datagrid so that whenever an item is added to its itemssource the datagrid scrolls down to show the last item.

The datagrid is inside a datatemplate, so i cannot set the X:name property and access it directly from the codebehind.

What I have in mind is to use a datagrid event that fires when a row is added and has the grid scroll itself.

Here's some psuedo code that outlines how I have things set up:


UI.XAML exerpt

<TabControl ItemsSource="{Binding Parents}" x:Name="ProductsTab">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Key}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <DataGrid Margin="5" ItemsSource="{Binding Value.Children}">
                <DataGrid.Columns>
                    <Column Column definitions removed for your sanity/>
                </DataGrid.Columns>
            </DataGrid>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

UI.XAML.CS exerpt

public class UI
{
    //Thanks to Dr. WPF for the ObservableDictionary class
    public ObservableDictionary<string, Parent> Parents {get; set;}
}

Parent.CS

public class parent
{
    public ObservableCollection<Child> Children {get; set;}
}

The datagrids are not editable.

In case you're wondering, I have read the post "How to autoscroll on WPF datagrid" the code in that post would work for me if I could find an event that fires whenever an item is added to the datagrid itemssource.

Any Ideas?

2

2 Answers

0
votes

Combine the autoscrolling idea with the idea from this question or this MSDN thread: instead of listening to your grid's event to detect row additions, listen to the events from the ItemsSource.

Edit: Since you don't like that suggestion, you could try hooking LoadingRow, but I strongly suspect this will require EnableRowVirtualization = false in order to work (I haven't tried it). If your collection gets large, turning off row virutalization opens up the possibility of a serious performance hit.

0
votes

you can access the DataGrid, even if it is in a DataTemplate, by doing a 'search' in the visual tree : VisualTreeHelper.GetChildCount // VisualTreeHelper.GetChild , then test again the type until you find your grid. And you might seek with same kind of methods the ScrollBar, and then you can hook an event handler and use a code-behind logic.