WPF - 如何在ItemsControl的ItemTemplate中绑定到项索引?

25
有没有办法在ItemsControl的ItemTemplate中绑定到ItemIndex?
例如:
<ItemsControl ItemsSource="{Binding Path=ItemList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=ThisItemsIndex}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
3个回答

28

如果您没有使用任何类型的交替行样式,您可以尝试使用AlternationIndex来实现。将ItemsControl的AlternationCount设置为大于您项目的最大可能计数的值,然后使用它。

Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=(ItemsControl.AlternationIndex)}"

编辑:正如bradgonesurfing在评论中指出的,如果你正在使用虚拟化,则不建议使用此方法,因为它仅会对生成的项进行索引而不是整个列表。


6
不要这样做。请参考https://dev59.com/Omw15IYBdhLWcg3wmc4J#17962582 - bradgonesurfing
有帮助,但从0开始并不十分实用,除非用户界面设计是为程序员而设。我想大多数人希望它从1开始。 - Chris
@Chris 这就是值转换器的作用。 - Chris Bordeman

3

这里有一种方法可以在集合项上添加一个可绑定的索引。我基本上将我的项包装在一个带有索引的容器中,并使用自定义的ObservableCollection来接受这个包装器。

请注意,MoveItem没有被覆盖,但是为了完整的实现,必须覆盖它。

public class IndexedItemContainerCollection<T> : ObservableCollection<IndexedItemContainer<T>>
{
    public IndexedItemContainerCollection()
    {

    }

    public IndexedItemContainerCollection(IEnumerable<IndexedItemContainer<T>> collection)
        : base(collection)
    {
        var index = 0;
        foreach (var item in this)
        {
            item.Index = index;
        }
    }

    protected override void InsertItem(int index, IndexedItemContainer<T> item)
    {
        item.Index = index;
        base.InsertItem(index, item);
        foreach (var indexedItem in this.Where(x=>x.Index > index))
        {
            indexedItem.Index++;
        }
    }

    protected override void RemoveItem(int index)
    {
        base.RemoveItem(index);
        foreach (var indexedItem in this.Where(x => x.Index > index))
        {
            indexedItem.Index--;
        }
    }

}

public class IndexedItemContainer<T>
{
    public int Index { get; set; }
    public T Item { get; set; }
}

然后我扩展我的包装类,以获取一个可绑定的属性,我可以控制索引的显示方式:

public class NamedIndexedItemContainer<T> : IndexedItemContainer<T>
{
    public string Name
    {
        get { return string.Format("Item #{0}", Index + 1); }
    }
}

使用示例

XAML:

    <ComboBox ItemsSource="{Binding ItemList}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

代码:

private IndexedItemContainerCollection<MyItem> _itemList;
public IndexedItemContainerCollection<MyItem> ItemList
{
    get { return _itemList; }
    set { _itemList= value; OnPropertyChanged(); }
}


ItemList = new IndexedItemContainerCollection<MyItem>();
var newItem = new NamedIndexedItemContainer<MyItem>() { Item = new MyItem() { ... } };
ItemList.Add(newItem);

当然,任何与实际 MyItem 实例的绑定都必须通过 IndexedItemContainer 的 Item 属性进行。

谢谢。通常我不喜欢从ObservableCollection<T>继承,但是如果将来需要类似的东西,我会记住这个的 :) - Rachel

2

值得注意的是,还有另一种实现方法:使用自定义转换器。这种方法稍微复杂一些,但您不必担心 AlternationCount/Index。

public sealed class ArrayWrapperConverter : IValueConverter
{
    private static readonly Type ArrayWrappingHelperType = typeof(ArrayWrappingHelper<>);

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return null;
        }

        Type valueType = value.GetType();
        if (!valueType.IsArray)
        {
            return DependencyProperty.UnsetValue;
        }

        Type elementType = valueType.GetElementType();
        Type specificType = ArrayWrappingHelperType.MakeGenericType(elementType);

        IEnumerable wrappingHelper = (IEnumerable) Activator.CreateInstance(specificType, value);
        return wrappingHelper;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

internal class ArrayWrappingHelper<TValue> : IEnumerable
{
    private readonly TValue[] _array;

    public ArrayWrappingHelper(object array)
    {
        _array = (TValue[]) array;
    }

    public IEnumerator GetEnumerator()
    {
        return _array.Select((item, index) => new ArrayItemWrapper<TValue>(_array, index)).GetEnumerator();
    }
}

public class ArrayItemWrapper<TValue>
{
    private readonly TValue[] _array;
    private readonly int _index;

    public int Index 
    {
        get { return _index; }
    }

    public TValue Value
    {
        get { return _array[_index]; }
        set { _array[_index] = value; }
    }

    public ArrayItemWrapper(TValue[] array, int index)
    {
        _array = array;
        _index = index;
    }
}

使用示例:

<Window x:Class="WpfArrayBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:WpfArrayBinding.Converters"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <c:ArrayWrapperConverter x:Key="ArrayWrapperConverter" />

            <x:Array Type="{x:Type s:String}" x:Key="MyArray">
                <s:String>Foo</s:String>
                <s:String>Bar</s:String>
                <s:String>Baz</s:String>
            </x:Array>
    </ResourceDictionary>
    </Window.Resources>

    <ItemsControl ItemsSource="{Binding Source={StaticResource MyArray}, Converter={StaticResource ArrayWrapperConverter}}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>                
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding Index}" />
                    <TextBox Text="{Binding Value}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Window>

谢谢,下次我需要在ItemsControl中使用ItemIndex时,我会尝试一下这个方法 :) 你有没有遇到过性能方面的问题? - Rachel
不,但我只在相对较小的数组中使用过它。 - Maciej Wozniak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接