获得DateTemplate中的element
比较困难的是用DataTemplate.FindName(string name,parent),需要知道这个datatemplate visual tree中的直系父亲,只要就是查找这个父亲了。
例子:
<DataTemplate x:Key="myDataTemplate">
<TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
ItemsControl通过ItemContainerGenerator产生items, 从一个dataItem到visual tree item,能够用ItemContainerGenerator.ContainerFromIndex 或者 ItemContainerGenerator.ContainerFromItem获得一个 container,如一个TreeViewItem.相反还有ItemContainerGenerator.ContainerFromItem,ItemContainerGenerator.ItemFromContainer方法来从container获得index或者dataItem.
重新转到获得dataTemplate, 例子:
// Getting the currently selected ListBoxItem // Note that the ListBox must have // IsSynchronizedWithCurrentItem set to True for this to work ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem)); // Getting the ContentPresenter of myListBoxItem ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem); // Finding textBlock from the DataTemplate that is set on that ContentPresenter DataTemplate myDataTemplate = myContentPresenter.ContentTemplate; TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter); // Do something to the DataTemplate-generated TextBlock MessageBox.Show("The text of the TextBlock of the selected list item: " + myTextBlock.Text);
FindVisualChild方法:
private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is childItem) return (childItem)child; else { childItem childOfChild = FindVisualChild<childItem>(child); if (childOfChild != null) return childOfChild; } } return null; }
参考:
http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspxhttp://msdn.microsoft.com/en-us/library/bb613579.aspx