I have an ItemsControl that uses DataGrid in its template like this:
Need to search the VisualTree if you want to do something like that. Though I recommend reading a bit more on MVVM patterns. But here is what you want.
using System.Windows.Media;
private T FindFirstElementInVisualTree<T>(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<T>(child);
if (result != null)
return result;
}
}
return null;
}
Now after you set your ItemsSource and the ItemControl is ready. I'm just going to do this in the Loaded
event.
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<DataGrid>(item);
// at this point dg should be the DataGrid of the first item in your list
}