2008年5月21日 星期三

VisualTree Search

Check this:

http://blogs.msdn.com/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx

1. Get a hold of the current list item:

// Note that the ListBox must have

// IsSynchronizedWithCurrentItem set to True for this to work

ListBoxItem myListBoxItem =

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

2. Find the ContentPresenter of that list item by walking through its visual tree [1]:

ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

3. Now you can call FindName on the DataTemplate of that ContentPresenter:

DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;

TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);

[1] The FindVisualChild method called in step 2:

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;

}

沒有留言: