saikamesh
saikamesh

Reputation: 4629

Metro app - How to scroll to a particular control in StackPanel

In my C# windows 8 metro app, I have added a StackPanel on top of a ScrollViewer. I have some controls added horizontally on a StackPanel. Once all the controls are added on top of the StackPanel, I want to scroll to a specific control and show that control(setting the focus to a particular control).

Please tell me whether doing this is possible. I looked at the ScrollViewer class reference, there is a method called ScrollToHorizontalOffset, but I have no idea how to get the offset of a particular control added on StackPanel.

There is no such method in StackPanel which returns the offset of it's child.

Upvotes: 1

Views: 1542

Answers (2)

Jeff Brand
Jeff Brand

Reputation: 5633

I would recommend that you look at something like a ListView if possible, since it will allow you to scroll to a particular item in the list. But, if that is not feasible, you can do something like this...

function scrollTo(int childIndex)
{
            double offset = 0;
            for (int i = 0; i < childIndex; i++)
            {
                var element = stack.Children[1] as FrameworkElement;
                offset += element.ActualWidth + element.Margin.Left + element.Margin.Right;
            }

            if (offset > scroll.ActualWidth)
                scroll.ScrollToHorizontalOffset(offset - scroll.ActualWidth);
            else
                scroll.ScrollToHorizonalOffset(0);
}

scroll is your scrollviewer and stack is your stack panel. Assuming a horizontal layout. This will only bring the item into the scrollwindow, it will not scroll it to the far left edge since that is not always possible.

Upvotes: 1

N_A
N_A

Reputation: 19897

The stackpanel lays out the control according to how much space they have requested, so you can calculate the offset by iterating through all the children before your control and calculating how much space each on takes up.

Upvotes: 0

Related Questions