这是一个黑客解决方案。我们可以将值转换与数据绑定结合使用。所以第一步是声明我们的 ValueConvertor:
public class ListItemToPositionConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var item = value as ListBoxItem;
if (item != null)
{
var lb = FindAncestor<ListBox>(item);
if (lb != null)
{
var index = lb.Items.IndexOf(item.Content);
return index;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
在您想要此静态方法的任何位置声明以获得 ListBox 父级:
public static T FindAncestor<T>(DependencyObject from) where T : class
{
if (from == null)
return null;
var candidate = from as T;
return candidate ?? FindAncestor<T>(VisualTreeHelper.GetParent(from));
}
然后在 ListBox.Resources 中声明我们的转换器,如下所示:
<ListBox.Resources>
<YourNamespace:ListItemToPositionConverter x:Key="listItemToPositionConverter"/>
</ListBox.Resources>
最后 - 数据模板:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Converter={StaticResource listItemToPositionConverter}}"/>
<Label Content="{Binding Path=DisplayName}"></Label>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Note:在此示例中,项目将从 0(零)开始编号,您可以在 Convert 方法中通过向结果添加 1 来更改它。
希望这可以帮助...