WPF ListBox 获取序号

查了一大圈教程,也没有找到一个好的方法,这里我写下我的办法吧
这里顺便也有ListBox子节点自适应父节点宽度的写法

首先给Button的Tag标签,绑一个我们自己已知的属性,也可以我们在数据源直接加一个Index属性

 <ListBox x:Name="ListBox_gameList" >
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Width="auto" >
                        <Label Content="{Binding Path=GameName}" HorizontalAlignment="Left"/>
                        <Button Content="删除" Click="Button_ClickDelete" HorizontalAlignment="Right" MinWidth="40"
                                Tag="{Binding Path=Name}"/>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

然后在点击事件中获取这个按钮的Tag


private void Button_ClickDelete(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;
    for (int i = 0; i < EditorData.CurrentGameChannelList.Count; i++)
    {
        ChannelInfo info = EditorData.CurrentGameChannelList[i];

        if (info.Name == (string)btn.Tag)
        {
            EditorData.CurrentGameChannelList.RemoveAt(i);
            return;
        }
    }
}

kisence

潮落江平未有风。