从绑定项中获取ItemsControl中的DataGrid
我有一个ItemsControl在其模板中使用DataGrid,如下所示:
ItemsControl绑定到我的模型中的Dists
属性,如下所示:
ObservableCollection<Dictionary> Dists;
如何获取与Dists属性中的项对应的DataGrid? 我试过这个代码,它给了我一个ContentPresenter,但我不知道如何从中获取DataGrid:
var d = Dists[i]; var uiElement = (UIElement)icDistribucion.ItemContainerGenerator.ContainerFromItem(d);
我试过用VisualHelper.GetParent
向上走树但找不到DataGrid。
如果你想做类似的事情,需要搜索VisualTree。 虽然我建议阅读更多有关MVVM模式的内容。 但这就是你想要的。
using System.Windows.Media; private T FindFirstElementInVisualTree(DependencyObject parentElement) where T : DependencyObject { var count = VisualTreeHelper.GetChildrenCount(parentElement); if (count == 0) return null; for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(parentElement, i); if (child != null && child is T) { return (T)child; } else { var result = FindFirstElementInVisualTree (child); if (result != null) return result; } } return null; }
现在,在设置ItemsSource并且ItemControl准备好之后。 我将在Loaded
事件中执行此操作。
private void icDists_Loaded(object sender, RoutedEventArgs e) { // get the container for the first index var item = this.icDists.ItemContainerGenerator.ContainerFromIndex(0); // var item = this.icDists.ItemContainerGenerator.ContainerFromItem(item_object); // you can also get it from an item if you pass the item in the ItemsSource correctly // find the DataGrid for the first container DataGrid dg = FindFirstElementInVisualTree(item); // at this point dg should be the DataGrid of the first item in your list }