tags:

views:

1163

answers:

2

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);
        }
    }
+1  A: 

I don't think an attached property will help you in this case. Your attached property will always have the value of "Default" since I don't think you are setting the property to something else. OnItemIndexChanged is only called if the ItemIndex property had been modified via Binding or directly in XAML or code.

I would use a value converter in the same way as the link you posted above.

MSDN has a sample on creating a value onverter: http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

John Z
A: 

Thank you very much for your response. I've actually been down that road and was having difficulties with the TextBlock refreshing its index when the listbox items are shuffled around. Is there a simple workaround or this is a limitation? Thanks again!

-Joel

Joel