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