2014-09-25 68 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

相關問題