【转载 http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a01eb1d5-cfc1-47fc-a8e5-45f7f02e8119】
How do I programmatically find a control inside an itemtemplates datatemplate, e.g. how do I find the checkbox inside the following XAML from the codebehind file..
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="KontoFeltCheckBox"
Checked="KontoFeltCheckBox_Checked"
></CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
You could walk the ListBoxItem Visual-Tree to find it’s ContentPresenter, and then find CheckBox from ContentPresenter’s ContentTemplate. Please see example below:
Markup:
<Window x:Class="FindControlInsideDataTemplate.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ListBox Name="myListBox" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="KontoFeltCheckBox" Checked="KontoFeltCheckBox_Checked">
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Test" Click="Button_Click"/>
</StackPanel>
</Window>
Code:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace FindControlInsideDataTemplate
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new List<Person>()
{
new Person(){Name = "Tom"},
new Person(){Name = "Ken"},
new Person(){Name = "Peter"}
};
}
private void KontoFeltCheckBox_Checked(object sender, RoutedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromIndex(0));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
CheckBox target = (CheckBox)myDataTemplate.FindName("KontoFeltCheckBox", myContentPresenter);
}
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;
}
}
public class Person
{
public string Name { set; get; }
}
}