Edward_jie

for you, my Hall of Frame

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

In this post I am going to talk about how to access a Control inside the ListBox ItemPanelTemplate/DataTemplate in Silverlight for WP7.

Question: How to access/modify a specific Control placed inside ListBox ItemTemplate/DataTemplate?

When you have a data bound control, lets say for example ListBox we usually add some custom DataTemplate. So sometimes you try to access and modify any element inside DataTemplate. 

Answer: Actually you can this by using the VisualTreeHelper which provides utility methods that can used to traverse object relationships (along child object or parent object axes) in the Silverlight for WP7 visual tree.

To begin with lets create a sample Windows Phone 7 project , add a data bound to a collection of strings ListBox  with the following ItemsTemplate and ItemsPanel:

1
2
3
4
5
6
7
8
9
10
11
<ListBox x:Name="list">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <ToggleButton x:Name="btnToggle"/>
                <CheckBox x:Name="cbx"/>
                <TextBlock Text="{Binding}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
1
2
List<string> dataSource = new List<string> {"Item1","Item2","Item3" };
this.list.ItemsSource = dataSource;

How to Access a specific Control placed inside  ListBox ItemsTemplate

Here is how you can implement a Generic method that can find the first element from any particular type inside the Visual Tree:

Example1:  Use a Generic method to find first element of particular type:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
    var count = VisualTreeHelper.GetChildrenCount(parentElement);
    if (count == 0)
        return null;
  
    for (int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(parentElement, i);
          
        if (child != null && child is T)
        {
            return (T)child;
        }
        else
        {
            var result = FindFirstElementInVisualTree<T>(child); 
            if (result != null)
                return result;
            
        }
    }
    return null;
}

Sample usage:

We will first get an instance of the second Listbox item using ItemContainerGenerator. (Note that we have to use ItemContainerGenerator because our ListBox is databound!). Next we will find the CheckBox control which is inside the ListBox itema and will set its IsChecked property to true:

1
2
3
ListBoxItem item = this.list.ItemContainerGenerator.ContainerFromIndex(2) as ListBoxItem;
CheckBox tagregCheckBox = FindFirstElementInVisualTree<CheckBox>(item);
tagregCheckBox.IsChecked = true;

Example2:  Use a simple method to find first element of a particular type that meets a condition:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void SearchVisualTree(DependencyObject targetElement)
{
    var count = VisualTreeHelper.GetChildrenCount(targetElement);
    if (count == 0)
        return;
  
    for (int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(targetElement, i);
        if (child is TextBlock)
        {
            TextBlock targetItem = (TextBlock)child;
              
            if (targetItem.Text == "Item2")
            {
                targetItem.Foreground = new SolidColorBrush(Colors.Green);
                return;
            }
        }
        else
        {
            SearchVisualTree(child);
        }
    }
}

Sample usage:

This code will find the first TextBlock element in the ListBox which has Text set to "Item2"

1
SearchVisualTree(this.list);

NOTE: In this way you can implement your own methods that find all element in the VisualTree of  a type,  you can add another condition, etc.

I hope that the post was helpful. The full source code is available here.

原文链接:http://www.windowsphonegeek.com/tips/how-to-access-a-control-placed-inside-listbox-itemtemplate-in-wp7

posted on 2011-12-13 16:23  Edward_诺  阅读(953)  评论(2编辑  收藏  举报