Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to access a ListBox inside a Pivot in windows phone 7?
    text
    copied!<p>i have a a Pivot that has a ListBox defined as its Pivot.ItemTemplate as the following.</p> <pre><code>&lt;controls:Pivot x:Name="pivot"&gt; &lt;controls:Pivot.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;ListBox x:Name="listBox"&gt; ... &lt;/ListBox&gt; &lt;/DataTemplate&gt; &lt;/controls:Pivot.ItemTemplate&gt; &lt;/controls:Pivot&gt; </code></pre> <p>how do i programmatically access the corresponding ListBox control corresponding to the Pivot.SelectedItem or Pivot.SelectedIndex?</p> <p>i tried something similar to this link <a href="http://www.windowsphonegeek.com/tips/how-to-access-a-control-placed-inside-listbox-itemtemplate-in-wp7" rel="nofollow">http://www.windowsphonegeek.com/tips/how-to-access-a-control-placed-inside-listbox-itemtemplate-in-wp7</a>. </p> <pre><code>var count = VisualTreeHelper.GetChildrenCount(pivotItem); for(int i=0; i &lt; count; i++) { var child = VisualTreeHelper.GetChild(pivotItem, i); if(child is ListBox) { //do something } else { Debug.WriteLine(child.GetType()); } } </code></pre> <p>for some reason, i get System.Windows.Controls.Grid on the Debug.WriteLine.</p> <p>the reason why i need to get a handle or access the ListBox inside the Pivot (that is currently on display/selected), is because i need to reset its view (scroll it back to the top). the ListBox is data bound to ObservableCollection, and when i update the collection, the scroll position needs to be placed back to the top; otherwise, everything works (data binding/visual display), except now the view is stuck in the middle or where the user currently is. if there's an easier way to do this without getting a handle on the ListBox, i'm open to that solution as well.</p> <p>just in case anyone is interested, i tinkered and came up with something that works specifically for my case. the code is below. basically, i had to get the PivotItem first.</p> <pre><code>PivotItem pivotItem = pivot.ItemContainerGenerator.ContainerFromItem(myObject) as PivotItem; </code></pre> <p>i then created a local variable to store the ListBox (if it's found) and recursed the tree view model.</p> <pre><code>ListBox listBox = null; Recurse(pivotItem, ref listBox); </code></pre> <p>and my Recurse function looks like the following.</p> <pre><code>private void Recurse(DependencyObject obj, ref ListBox listBox) { if(obj is ListBox) { listBox = obj as ListBox; return; } var count = VisualTreeHelper.GetChildrenCount(obj); for(int i=0; i &lt; count; i++) { var child = VisualTreeHelper.GetChild(obj, i); Recurse(child, ref listBox); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload