</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MyWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Person> lst = new List<Person>()
{
new Person(){ Id=1, Name="zhangsan", HasJob=false, skill="C#"},
new Person(){ Id=2, Name="lisi", HasJob=true, skill="C#"},
new Person(){ Id=3, Name="wangwu", HasJob=false, skill="wpf"},
new Person(){ Id=4, Name="maliu", HasJob=true, skill="C#"},
new Person(){ Id=5, Name="zhaoqi", HasJob=false, skill="wpf"},
};
}
private void Name_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = e.OriginalSource as TextBox;
ContentPresenter cp = tb.TemplatedParent as ContentPresenter;
Person p = cp.Content as Person;
lv.SelectedItem = p;
ListViewItem lvi = lv.ItemContainerGenerator.ContainerFromItem(p) as ListViewItem;
CheckBox cb = FindVisualChild<CheckBox>(lvi);
MessageBox.Show(cb.Name);
}
private ChildType FindVisualChild<ChildType>(DependencyObject obj) where ChildType : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is ChildType)
{
return child as ChildType;
}
else
{
ChildType childOfChild = FindVisualChild<ChildType>(child);
if (childOfChild!=null)
{
return childOfChild;
}
}
}
return null;
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string skill { get; set; }
public bool HasJob { get; set; }
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容