那么如何获取ListBox中的StackPanel这个子元素的值呢,又如何来对每个Item的背景色进行改变呢?我们可以用下面的方法来进行判断,首先获取当前系统所使用的背景色,然后遍历ListBox中的每个item,利用泛型函数对该ListBox的整个visual tree进行读取,根据需要选择StackPanel类型的控件(这里读者可以根据实际情况做改动。)
方法一:
var back = Application.Current.Resources["PhoneBackgroundColor"].ToString(); if (back == "#FF000000") { for (int i = 0; i < FirstListBox.Items.Count; i++) { ListBoxItem item = this.FirstListBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem; StackPanel border = FindFirstElementInVisualTree
{
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
if (result != null)
return result;
}
}
return null;
}
好了看看效果吧(只是个示例,更炫的效果还需要读者自己斟酌了呵呵)PS:背景我采用了两张图片。
![WP7中对ListBox的ItemTemplate中子元素的后台操作itemno](/Files/20116/5b623f83-61c6-4214-978c-4f2efdc0c8cf.png)
![WP7中对ListBox的ItemTemplate中子元素的后台操作itemno](/Files/20116/a52afa9d-468b-41ee-bba6-4f09a7017afe.png)
方法二:
还有个方法来进行操作,可以看下面方法,方法是参照WindowsPhoneGeek网站上的,大家也可以看看。
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 StackPanel) { StackPanel targetItem = (StackPanel)child; var back = Application.Current.Resources["PhoneBackgroundColor"].ToString(); if (back == "#FF000000") { targetItem.Background = new SolidColorBrush(Color.FromArgb(255, 34, 34, 34)); } else { targetItem.Background = new SolidColorBrush(Color.FromArgb(170, 255, 255, 255)); } } else { SearchVisualTree(child); } } }
调用的时候只需要用下面这个函数就可以了,看起来比第一个方法更简单:
this.SearchVisualTree(this.FirstListBox);
最新评论