您的位置:首页 > 其它

如何在WPF和Silverlight中取得DataTemplate中的命名元素

2010-01-26 09:44 591 查看
WPF

1.假如ListBox使用如下的DataTemplate

代码

ListBoxItem myListBoxItem =
(ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));

TextBlock myTextBlock = FindFirstVisualChild<TextBlock>(_myListBoxItem , "textBlock");
MessageBox.Show("The text of the TextBlock of the selected list item: "
+ myTextBlock.Text);

private childItem FindVisualChild<childItem>(DependencyObject obj,String childName)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem && child.GetValue(NameProperty).ToString()==childName)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child,childName);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: