在ItemCollection CollectionChanged事件中获取ItemsControl



我的项目控制:

 <ItemsControl x:Name="MyItemsControl"  Style="{StaticResource ItemsControlStyle}" />
 <Style TargetType="{x:Type ItemsControl}" x:Key="ItemsControlStyle">
      <Setter Property="ItemTemplate" Value="{StaticResource ItemsControlDataItem}"></Setter>
 </Style>
 <DataTemplate x:Key="ItemsControlDataItem" >
      <Ellipse Width="45" Height="45"></Ellipse>
 </DataTemplate>

iv'e钩住了一个事件,以查看基础集合何时更改:

 ((INotifyCollectionChanged)MyItemsControl.Items).CollectionChanged += new NotifyCollectionChangedEventHandler(ClientWindow_CollectionChanged);

我需要的第一件事是提取拥有这个ItemCollection 的ItemsControl

第二件事是遍历所有数据项作为它们的DataTemplate,即作为Ellipse因为我不想对他们进行一些改造。

   void ClientWindow_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
   {
        // here i need to traverse and make my change , how do i extract the ellipse items  
        // how do i get the itemsControl associated with the ItemCollection which triggered this event                
            ItemCollection collection = sender as ItemCollection ;
            foreach (object item in collection)
            {
                //  here i would need the ellipse that the object represents 
                // EDIT : i'm guessing this is how i would get the ellipse    
                // but how would i get the itemsControl ?
                var ellipse = _itemsControl.ItemContainerGenerator.ContainerFromItem(item ) as Ellipse;
            }                    
   }

因此,为了澄清,我不想遍历集合并提取通过datatemplate分配的底层类型。

您可以通过调用以下代码来获得椭圆:

//  here i would need the ellipse that the object represents 
var container = control.ItemContainerGenerator.ContainerFromItem(item);
var ellipse = VisualTreeHelper.GetChild(container, 0);

最新更新