WPF ListBox bind to index of the item

▼魔方 西西 提交于 2019-12-08 18:03:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/259092/wpf-listbox-bind-to-index-of-the-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!