WPF ListBox绑定到项目的索引 [英] WPF ListBox bind to index of the item

查看:188
本文介绍了WPF ListBox绑定到项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很容易将某些内容绑定到ListBox的SelectedIndex
,但我希望ListBox中的每个项目都能够绑定到列表中的索引。

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>

我想将超链接的TAG属性绑定到相关项目的索引。
当用户单击超链接时,我可以使用该超链接的TAG属性来确定导致事件的项目。

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);

建议?

推荐答案

据我所知,没有一个属性表示您的项目的索引。如果您可以访问列表框绑定的项目的原始列表,则可以访问超链接的DataContext以确定项目的索引,如下所示:

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);

或者,您可以在超链接上调用ItemsControl.ContainerFromElement来获取与超链接相关联的ListBoxItem,找到ListBoxItem在ListBox中的位置,但它并没有真正让你没有你没有的东西。

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.

这篇关于WPF ListBox绑定到项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆