How to access a Control placed inside ListBox ItemTemplate in WP7(转)

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:

 

<ListBox x:Name="list"> 

 

<ListBox.ItemTemplate> 

 

<DataTemplate> 

 

<StackPanel> 

 

<ToggleButton x:Name="btnToggle"/> 

 

<CheckBox x:Name="cbx"/> 

 

<TextBlock Text="{Binding}"/> 

 

</StackPanel> 

 

</DataTemplate> 

 

</ListBox.ItemTemplate> 

 

</ListBox>

 

 
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:

 

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:

 

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:

 

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"

 

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. Thefull source code is available here.

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

另外:修改listbox的datatemplate中的控件属性方法:

 

public static void SearchVisualTree(DependencyObject targetElement, int width,string Node)

        {

            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.Name == Node)

                        targetItem.Width = width;

                }

                else

                {

                    SearchVisualTree(child, width,Node);

                }

            }

        }

调用:SearchVisualTree(listbox1,500,"textBox2");

WP8_访问ListBox中的Item项中的某个元素的更多相关文章

  1. 每日一道 LeetCode (8):删除排序数组中的重复项和移除元素

    每天 3 分钟,走上算法的逆袭之路. 前文合集 每日一道 LeetCode 前文合集 代码仓库 GitHub: https://github.com/meteor1993/LeetCode Gitee ...

  2. Android 取得 ListView中每个Item项目的值

    首先我们须要创建 ListView .这里假定我们已经创建好了而且使用SimpleAdapter设置好了adapter数据,看一下我们的adapter ArrayList<HashMap< ...

  3. 【LeetCode】删除排序数组中的重复项&&移除特定元素【双指针,原地算法】

    给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成. 示例 1 ...

  4. PyQt(Python+Qt)学习随笔:树型部件的QTreeWidgetItem项中列不同角色数据的有关访问方法

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 树型部件QTreeWidget中的QTreeWidgetItem项中可以有多列数据,每列数据可以根据 ...

  5. Android处理ListView中的Item中的Button按钮不能点击的问题

    问题描述:ListView列表中的Button按钮按钮不能点击 解决办法:在ListView中的Item项的布局文件中加上:android:descendantFocusability="b ...

  6. 【WPF】拖拽ListBox中的Item

    整理了两个关于WPF拖拽ListBox中的Item的功能.项目地址 https://github.com/Guxin233/WPF-DragItemInListBox 需求一: 两个ListBox,拖 ...

  7. (1)FluidMoveBehavior 之 ListBox 中详细内容项飞出来

    在 Blend 中集成了很多行为,首先需要了解一下Behaviors(行为)的几个关键点: (1)Behaviors(行为)是可复用代码集合,可以被任何对象附加使用: (2)设计人员和开发人员可以使用 ...

  8. PyQt(Python+Qt)学习随笔:QTreeWidgetItem项中列的复选状态访问方法

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 树型部件QTreeWidget中的QTreeWidgetItem项,项中每列数据都可以单独设置复选状 ...

  9. GridView 中Item项居中显示

    直接在GridView中设置 android:gravity="center"这个属性是不起作用的.要在你adapter中的布局文件中设 置android:layout_gravi ...

随机推荐

  1. HDU 1671 Phone List (Trie·数组实现)

    链接:http://blog.csdn.net/acvay/article/details/47089657 题意  给你一组电话号码  判断其中是否有某个电话是另一个电话的前缀 字典树的基础应用   ...

  2. HDU Count the string+Next数组测试函数

    链接:http://www.cnblogs.com/jackge/archive/2013/04/20/3032942.html 题意:给定一字符串,求它所有的前缀出现的次数的和.这题很纠结,一开始不 ...

  3. [Mysql] MySQL配置文件my.cnf的理解

    一.缘由 最近要接手数据库的维护工作,公司首选MySQL.对于MySQL的理解,我认为很多性能优化工作.主从主主复制都是在调整参数,来适应不同时期不同数量级的数据. 故,理解透彻my.cnf里的参数是 ...

  4. linux命令(6)crontab的用法和解析

    一,写入格式: * * * * *   command minute   hour   day   month   week   command 其中: minute: 表示分钟,可以是从0到59之间 ...

  5. Json--Android中数据文件解析(Json解析--从服务器端获取数据并且解析,显示在客户端上面)

    前面学习过了使用SAX解析XML数据(点击进入:SAX解析XML数据),今天学习Json解析: 首先说一下Json数据的最基本的特点,Json数据是一系列的键值对的集合,和XML数据来比,Json数据 ...

  6. android 基本知识

    307966990 lyd@itcast.com 13716040037 李印东 东东 通信技术: 1G 模拟制式 语音通话. 2G GSM, CDMA 收发短信和邮件. 2.5G GPRS, EDG ...

  7. List集合去重的一种方法 z

    需要对一个List<Model>集合去重,情况是该集合中会出现多个Name属性值相同的,但是其他属性值不同的数据. 在这种情况下,需求要只保留其中一个就好. 我觉得遍历和HashSet都不 ...

  8. struts2中action中的通配符

    struts中一个正常的最普通不过的action是这样子的 <package name="default1" namespace="/gys" exten ...

  9. gRPC 的 RoadMap 20160325 更新

    gRPC是一个高性能.通用的开源RPC框架,其由Google主要面向移动应用开发并基于HTTP/2协议标准而设计,基于ProtoBuf(Protocol Buffers)序列化协议开发,且支持众多开发 ...

  10. sqlite报错OutOfMemory

    如 java.sql.SQLException: out of memory at org.sqlite.DB.throwex(DB.java:252) at org.sqlite.NestedDB. ...