1
使用this posting作为参考,我尝试通过实现附加属性来显示列表框项目的索引。我将首先承认,我并不完全理解附属财产如何解决这个问题,但我希望在成功实施该解决方案后它会变得清晰。在花了无数小时解决问题之后,无论是否通过附加属性,我都在寻找一些帮助。此时,它使用默认字符串(“Default”),但它似乎并未评估其他函数。这是我到目前为止有:通过附加属性获取列表框项目索引
在WPF:
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}},
Mode=OneWay,
Path=(Silhouette_Controls_ThumbnailListbox:ListBoxItemIndex.ItemIndex)}"
TextAlignment="Center"
VerticalAlignment="Bottom"
HorizontalAlignment="Center" />
依赖地产类在C#
public class ListBoxItemIndex : DependencyObject
{
public static readonly DependencyProperty ItemIndexProperty =
DependencyProperty.RegisterAttached(
"ItemIndex",
typeof(string),
typeof(ListBoxItemIndex),
new PropertyMetadata("Default", new PropertyChangedCallback(OnItemIndexChanged)));
public static string GetItemIndex(DependencyObject element)
{
return (string)element.GetValue(ItemIndexProperty);
}
public static void SetItemIndex(DependencyObject element, string value)
{
element.SetValue(ItemIndexProperty, value);
}
private static void OnItemIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ListBoxItem item = d as ListBoxItem;
ListBox view = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
int index = view.ItemContainerGenerator.IndexFromContainer(item);
}
}