get ItemsControl in ItemCollection CollectionChanged event

时光怂恿深爱的人放手 提交于 2019-12-08 04:48:43

问题


my 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 hooked an event to see when the underlying collection as changed :

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

the first thing i need is a way to extract the ItemsControl which owns this ItemCollection

the second thing is to traverse all the data items as their DataTemplate , i.e. as Ellipse since i wan't to perform some Transformation on them .

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

so just to clarify i wan't to traverse the collection and extract the underlying type assigned through the datatemplate .


回答1:


You can get the ellipse by calling the following code:

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


来源:https://stackoverflow.com/questions/9829513/get-itemscontrol-in-itemcollection-collectionchanged-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!