Obtain DataGrid inside ItemsControl from the binded item

后端 未结 1 1589
臣服心动
臣服心动 2021-01-25 06:37

I have an ItemsControl that uses DataGrid in its template like this:


    

        
相关标签:
1条回答
  • 2021-01-25 06:52

    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
    
    }
    
    0 讨论(0)
提交回复
热议问题