有没有办法从ItemsControl的ItemTemplate中绑定到ItemIndex?
例如:
<ItemsControl ItemsSource="{Binding Path=ItemList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=ThisItemsIndex}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud) 有没有办法获取当前ItemsControl
项目的索引WPF
?
例如,我想做类似的事情:
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding current_index}">
</TextBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
所以在此之后,第一个TextBox
将显示文本"0"
,第二个"1"
,第三个"2" ...
.
在WPF中创建ViewModel时,有时需要将ObservableCollection
(源集合)中可用的数据转换为扩展/限制/投影原始元素(目标集合)的包装元素集合,同时元素的数量和顺序始终镜像原始集合.
就像Select扩展方法一样,除了它不断更新,因此可以用于WPF绑定.
如果在索引x处将元素添加到源,则会在目标集合中的相同索引x处添加相同元素的Wrapper.如果在源集合中删除了索引y处的元素,则会在目标集合中删除索引y处的元素.
说有一个ObservableCollection<ClassA>
,但我需要绑定的是ReadOnlyObservableCollection<ClassB>
(或等效的),其中ClassB
- > ClassA
如下:
class ClassB : INotifyPropertyChanged, IDisposable
{
public ClassB(ClassA a)
{
Wrapped = a;
(Wrapped as INotifyPropertyChanged).PropertyChanged+=WrappedChanged;
}
public ClassA Wrapped { get; private set; }
public int SomeOtherProperty { get { return SomeFunction(Wrapped); }
WrappedChanged(object s, NotifyPropertyChangedArgs a) { ... }
...
}
Run Code Online (Sandbox Code Playgroud)
我可以自己写TemplatedTransformCollectionWrapper
,我可以写这个:
ObservableCollection<ClassA> source;
TemplatedTransformCollectionWrapper theCollectionThatWillBeUsedInABinding
= TemplatedTransformCollectionWrapper(source, classA => new ClassB(classA));
Run Code Online (Sandbox Code Playgroud)
TemplatedTransformCollectionWrapper理想地包装所有实现INotifyCollectionChanged
并正确处理原始包装集合的所有可能的添加,删除和替换操作的集合.
TemplatedTransformCollectionWrapper
正确编写并不是一件轻而易举的事情,它似乎是其他人已经做过的事情,也许它甚至是核心框架的一部分.但我找不到它.
我希望能够在DataTemplate中显示索引值,但我不希望数据由模型或视图模型保留或支持.换句话说,如果OC中项目的顺序发生变化,我不想重新计算索引.该值应与OC中的基础索引固有关联.如果索引从0开始是可以的(实际上,我希望它).
其他人使用的一种方法是AlternationIndex AP,但这在某些情况下有其自身的缺陷.
最后一个想法:我不禁想到转换器将在最终解决方案中发挥作用.
我的意思是,我有一个listBox,我将itemsSource属性放在列表中.我想在它的绑定中也显示索引.
我不知道这是否可以在WPF中使用.谢谢.