在Listbox.ItemTemplate(WPF C#)中查找控件

我在StackPanel找到正确的TextBlock控件时遇到了一些问题。 我的标记:

                  

我的双击代码:

 private void lstTimeline_MouseDoubleClick(object sender, MouseButtonEventArgs e) { ListBoxItem lbi = (lstTimeline.SelectedItem as ListBoxItem); StackPanel item = lbi.FindName("stkPanel") as StackPanel; if (item != null) MessageBox.Show("StackPanel null"); TextBlock textBox = item.FindName("lblScreenName") as TextBlock; if (textBox != null) MessageBox.Show("TextBlock null"); MessageBox.Show(textBox.Text); } 

StackPanel为空。 如何在SelectedItem找到正确的TextBlock

谢谢你的帮助。

 ListBoxItem myListBoxItem = (ListBoxItem)(lstUniqueIds.ItemContainerGenerator.ContainerFromIndex(lstUniqueIds.SelectedIndex)); ContentPresenter myContentPresenter = FindVisualChild(myListBoxItem); DataTemplate myDataTemplate = myContentPresenter.ContentTemplate; CheckBox target = (CheckBox)myDataTemplate.FindName("chkUniqueId", myContentPresenter); if (target.IsChecked) { target.IsChecked = false; } else { target.IsChecked = true; } 

函数FindVisualChild可以在MSDN页面上找到FrameworkTemplate.FindName方法 :

 private childItem FindVisualChild(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(child); if (childOfChild != null) return childOfChild; } } return null; } 

当您在寻找名称在模板中定义的内容时,可以使用特定的function。 试试这样:

 private void lstTimeline_MouseDoubleClick(object sender, MouseButtonEventArgs e) { ListBoxItem lbi = (lstTimeline.SelectedItem as ListBoxItem); StackPanel item = Template.FindName("stkPanel",lbi) as StackPanel; if (item != null) MessageBox.Show("StackPanel null"); TextBlock textBox = Template.FindName("lblScreenName",item) as TextBlock; if (textBox != null) MessageBox.Show("TextBlock null"); MessageBox.Show(textBox.Text); } 

Linq to xml带有get和set模型。

 var item = ... lstTimeline.SelectedIndex = -1; lstTimeline.ItemsSource = item;