本文介绍了在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钩了一个事件,以查看基础集合何时更改:

iv'e hooked an event to see when the underlying collection as changed :

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

我需要做的第一件事是提取拥有此ItemCollection的ItemsControl的方法

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

第二件事是将所有数据项作为其DataTemplate遍历,即作为Ellipse因为我不想对它们执行一些转换.

the second thing is to traverse all the data items as their DataTemplate , i.e. as Ellipsesince 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;
            }
   }

因此,为了澄清起见,我将不遍历集合并提取通过datatemplate分配的基础类型.

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

推荐答案

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

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

这篇关于在ItemCollection CollectionChanged事件中获取ItemsControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:21