Edward_jie

for you, my Hall of Frame

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  92 随笔 :: 45 文章 :: 539 评论 :: 43万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 26 27 28 29
30 31 1 2 3 4 5

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   Edward_诺  阅读(954)  评论(2编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示