Using this posting as reference, I am attempting to display a Listbox item's index by implementing an attached property. I'll be the first to admit that I don't entirely understand how an attached property will solve this problem but I was hoping it would become clear after successfully implementing the solution. After spending countless hours on the problem, I'm looking for a little help whether it be through an attached property or not. At this point, it uses the default string ("Default") but it doesn't appear to be evaluating the other functions. Here's what I have so far:
In 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" />
Dependency Property Class in 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);
}
}