How to access Generated WPF controls after Data Binding
Please consider the following XAML code:
<ListBox Name="listBox1" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Border Name="border1"&开发者_StackOverflow社区gt;
<TextBlock Text="{Binding}" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and we assign a simple array to it:
listBox1.DataContext = new[] { "A", "B", "C" };
Now the question is how we can access the generated objects for Border (or TextBlock instances)?
- It is not possible by "border1". It does not exist.
listBox1.ItemContainerGenerator.ContainerFromIndex(0)
returns a ListBoxItem but content of that ListBoxItem is of type String.FindName("border1")
returns null
Update: What I expect to find are 3 instances of Border (and 3 TextBlocks, one in each Border).
Once you get the ListBoxItem, you need to walk the visual tree to find what your looking for.
Dr WPF has some great articles about it here
Here is the code from that article to search for a descendant of a particular type
public static Visual GetDescendantByType(Visual element, Type type)
{
if (element.GetType() == type) return element;
Visual foundElement = null;
if (element is FrameworkElement)
(element as FrameworkElement).ApplyTemplate();
for (int i = 0;
i < VisualTreeHelper.GetChildrenCount(element); i++)
{
Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
foundElement = GetDescendantByType(visual, type);
if (foundElement != null)
break;
}
return foundElement;
}
You can access it like so:
DataTemplate dt = this.listBox1.ItemTemplate;
Border border = dt.LoadContent() as Border;
// Do something with border...
精彩评论