Wpf 在ItemCollection CollectionChanged事件中获取ItemsControl

Wpf 在ItemCollection CollectionChanged事件中获取ItemsControl,wpf,itemscontrol,itemscollection,Wpf,Itemscontrol,Itemscollection,我的项目控件: <ItemsControl x:Name="MyItemsControl" Style="{StaticResource ItemsControlStyle}" /> <Style TargetType="{x:Type ItemsControl}" x:Key="ItemsControlStyle"> <Setter Property="ItemTemplate" Value="{StaticResource ItemsCont

我的项目控件:

 <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>
我需要的第一件事是提取拥有此ItemCollection的ItemsControl的方法

第二件事是遍历所有数据项作为其数据模板,即椭圆 因为我不想对它们进行一些转换

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

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

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

在本例中,我只获得了检查器的集合,每个项都是一个检查器,并且是我试图引用的椭圆项的DataContext。请理解,在本例中,我甚至没有对ItemsControl本身的引用,你能想出一种从ItemCollection引用items控件的方法吗?@eranotzer你必须在代码中引用MyItemsControl,如果您有多个ItemsControl,则必须保留这些控件的映射,并将集合与每个控件的映射与ItemControl.Items进行比较。不幸的是,ItemCollection未公开其对其父控件的引用。在这种情况下,我只获取检查程序集合,每个项都是检查程序,和是我试图引用的椭圆项的DataContext。请理解,我甚至没有对ItemsControl本身的引用。在这种情况下,您能想出一种从ItemCollection引用items控件的方法吗?@eranotzer您必须在后面的代码中引用MyItemsControl,如果您有多个ItemsControl,则必须保留这些控件的映射,并将集合与每个控件的映射比较为ItemControl.Items。不幸的是,ItemCollection未公开其对其父控件的引用。