wpf 在ListVIew CellTemplate对应的DataTemplate里面查找元素


    
        
            
            
            
            
        

        
            
        
        
            
        
        
            
        
    
    
        
            
                
                    
                    
                    
                    
                
            
        
        
    
   

  

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 WpfApp5
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TxtName_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = e.OriginalSource as TextBox;
            ContentPresenter cp = tb.TemplatedParent as ContentPresenter;
            Student s = cp.Content as Student;
            this.lstViewStu.SelectedItem = s;

            ListViewItem item = this.lstViewStu.ItemContainerGenerator.ContainerFromItem(s) as ListViewItem;
            CheckBox checkBox = FindVisulChild(item);
            MessageBox.Show(checkBox.Name);

        }

        private ChildType FindVisulChild(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 = FindVisulChild(child);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
            }
            return null;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp5
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Skill { get; set; }
        public bool HasJob { get; set; }
    }
}

 

你可能感兴趣的:(WPF)