Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ListBox bind to index of the item

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?

like image 977
TimothyP Avatar asked Nov 03 '08 16:11

TimothyP


1 Answers

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.

like image 136
Amanda Mitchell Avatar answered Sep 19 '22 19:09

Amanda Mitchell