WPF ListBox bind to index of the item
Asked Answered
M

1

7

It's easy to bind something to the SelectedIndex of the ListBox, but I want every item in the ListBox be able to bind to it's index in the list.

Might sound weird, so here's what I'm trying to do:

<DataTemplate x:Key="ScenarioItemTemplate">
<Border
    Margin="8,2,8,2"
    Background="#FF3C3B3B"
    BorderBrush="#FF797878"
    BorderThickness="2"
    CornerRadius="5">
    <DockPanel>
        <DockPanel DockPanel.Dock="Top" Margin="0,2,0,0">
            <Label HorizontalAlignment="Left"
                   DockPanel.Dock="Left"
                   FontWeight="Heavy"
                   Foreground="White"
                   Content="{Binding Path=Position}"
                   MinWidth="50"/>

            <Label
                   Content="{Binding Path=Name}"
                   DockPanel.Dock="Left"
                   FontWeight="Heavy"
                   Foreground="white"/>
            <Label 
                   Content="{Binding Path=Header}"
                   Foreground="white"
                   DockPanel.Dock="Left"/>

            <TextBlock HorizontalAlignment="Right" 
                       Background="#FF3C3B3B" 
                       DockPanel.Dock="Left" Foreground="White" FontWeight="Heavy">
                <Hyperlink Click="CloseHyperlink_Click" Tag="">X</Hyperlink>
            </TextBlock>

I want to bind the TAG property of the hyperlink to the index of the item in question. So that when the user clicks the hyperlink, I can determine what item caused the event using the TAG property of that hyperlink.

var hyperlink = (Hyperlink)sender;
var index = Convert.ToInt32(hyperlink.Tag);

Suggestions?

Millenary answered 3/11, 2008 at 16:1 Comment(0)
A
5

As far as I know, there isn't really a property that indicates the index of your item. If you have access to the original list of items to which your ListBox is bound, you could access the DataContext of your Hyperlink to determine the index of your item, like this:

var hyperlink = (Hyperlink)sender;
var item = (SourceType)hyperlink.DataContext;
int index = sourceList.IndexOf(item);

Alternatively, you could call ItemsControl.ContainerFromElement on the hyperlink to get the ListBoxItem associated with the Hyperlink and then find the ListBoxItem's position in the ListBox, but it doesn't really get you anything that you didn't already have.

Albigenses answered 3/11, 2008 at 16:17 Comment(1)
Well, actually just having item might be more than enough, because I want to do is delete it. Thnx!Millenary

© 2022 - 2024 — McMap. All rights reserved.