2014-09-25 71 views
1

我有一个使用数据网格在其模板这样一个ItemsControl:从绑定的项目获取DataGrid中的ItemsControl

<ItemsControl Name="icDists" ItemsSource="{Binding Dists}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <DataGrid ItemsSource="{Binding}" Width="150" Margin="5" AutoGenerateColumns="False" IsReadOnly="True"> 
       <DataGrid.Columns> 
        <DataGridTextColumn Header="Key" Binding="{Binding Key}" Width="1*" /> 
        <DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="1*" /> 
       </DataGrid.Columns> 
      </DataGrid> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

ItemsControl的被绑定到我的模型Dists属性,它看起来像这样:

ObservableCollection<Dictionary<string, string>> Dists; 

如何获取与Dists属性中的项目对应的DataGrid?我试过这个代码,这给了我一个ContentPresenter,但我不知道如何获得它的DataGrid中:

var d = Dists[i]; 
var uiElement = (UIElement)icDistribucion.ItemContainerGenerator.ContainerFromItem(d); 

我试着走了VisualHelper.GetParent树,但找不到数据网格。

+0

为什么你需要获取datagrid?如果你做了适当的绑定和通知,你需要的所有数据就在Dists集合中。 – 2014-09-26 01:38:56

+0

我需要手动调用DataGrid上的事件。 – user3557327 2014-09-29 15:49:47

回答

1

需要搜索VisualTree如果你想要做那样的事情。虽然我建议阅读更多的MVVM模式。但这是你想要的。


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; 
} 

现在,经过你设定的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<DataGrid>(item); 

    // at this point dg should be the DataGrid of the first item in your list 

} 
+0

谢谢,这正是我需要的。 – user3557327 2014-09-26 15:37:07

相关问题