我正在为ItemsControl实现附加属性。 面对我无法解决的任务。 我沿着视觉树从ItemTemplate中的UI元素爬到了ItemsControl。没问题。 但是我还需要在ItemsControl中定义用于生成项目的类型。 而且,这种类型在从ItemsControl派生的不同类中也不同。
让我们说说ListBox可以应用以下代码
public static bool GetIndexOn(FrameworkElement element)
{
int? index = (int?)element.Getvalue(IndexProperty);
if (index == null)
{
FrameworkElement parent = element;
// Search ListBoxItem
// But I need to find any type used to generate Item
while (!(parent is System.Windows.Controls.ListBoxItem || parent == null))
parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
if (parent == null)
return false;
// Saving the ListBoxItem
System.Windows.Controls.ListBoxItem listBoxItem = (System.Windows.Controls.ListBoxItem)parent;
// Search ItemsControl
while (!(parent is ItemsControl || parent == null))
parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
if (parent == null)
return false;
// Saving the ListBox
ItemsControl listBox = (ItemsControl)parent;
// Retrieving and storing index of ListBoxItem in ListBox
index = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);
element.Setvalue(IndexPropertyKey,index);
}
return false;
}