有如下控件
现要知道CheckBox是否选中,但是它是DataTemplate内部的控件,要如何访问到呢,MSDN上这样做的
所以方法如下
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; } private void Button_Click(object sender, RoutedEventArgs e) { ListBoxItem lbitem = null; ContentPresenter myContentPresenter = null; DataTemplate myDataTemplate = null; CheckBox ck = null; TextBlock tb = null; for (int i = 0; i < lb.Items.Count; i++) { lbitem = (ListBoxItem)(lb.ItemContainerGenerator.ContainerFromItem(lb.Items[i])); myContentPresenter = FindVisualChild (lbitem); myDataTemplate = myContentPresenter.ContentTemplate; ck = (CheckBox)myDataTemplate.FindName("ck", myContentPresenter) as CheckBox; if (ck.IsChecked == true) { tb = (TextBlock)myDataTemplate.FindName("tb", myContentPresenter) as TextBlock; MessageBox.Show(tb.Text); } } }
功能实现...
今天又遇到一个不一样的,DataGrid
好吧,上源代码
不错,我们要找的就是ck这个控件,并根据他是否选中来做一些业务处理,我主要是遍历,要获取某一行的checkbox是否被选中,请看这里
DataGridTemplateColumn _dataTemplate = dataGrid5.Columns[0] as DataGridTemplateColumn; FrameworkElement element = null; CheckBox ck=null; for (int i = 0; i < dataGrid5.Items.Count-1; i++) { element = _dataTemplate.GetCellContent(dataGrid5.Items[i]); ck=_dataTemplate.CellTemplate.FindName("ck",element) as CheckBox; if (ck.IsChecked == true) { MessageBox.Show(string.Format("StuName:{0}",(dataGrid5.Items[i] as Stu).StuName)); } }
ok,又搞定...