[英]How to know the index of the current element of ItemsRepeater in Avalonia?
I have the following code in my MainWindow.axaml:我的 MainWindow.axaml 中有以下代码:
<ItemsRepeater Items="{Binding ChannelCollection}">
<ItemsRepeater.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Value, Mode=TwoWay}" Content="{Binding Name}"></CheckBox>
</DataTemplate>
</ItemsRepeater.ItemTemplate>
</ItemsRepeater>
Here I bind to collection of Channels with Name
and Value
properties.在这里,我绑定到具有
Name
和Value
属性的 Channels 集合。 But actual content of my checkbox depends on its index in the collection.但我的复选框的实际内容取决于它在集合中的索引。 I don't want to resolve the Channel myself but want to use converter that maps index to the name.
我不想自己解析频道,而是想使用将索引映射到名称的转换器。 So far I have to know the element index from the axaml code.
到目前为止,我必须从 axaml 代码中知道元素索引。
I want to have something like this in my Checkbox tag:我想在我的复选框标签中有这样的东西:
Content="{Binding ItemsRepeater.CurrentIndex, Converter={StaticResource IdToNameConverter}}"
How can I do this?我怎样才能做到这一点?
You could use a multi value converter that converts your collection and the element to the name string:您可以使用多值转换器将您的集合和元素转换为名称字符串:
public class ElementIndexConverter : IMultiValueConverter
{
public object Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
{
return values[0] is IList list ? $"{list.IndexOf(values[1])}" : "-1";
}
}
Then in the view you have to use MultiBinding
and pass the collection and the object:然后在视图中,您必须使用
MultiBinding
并传递集合和 object:
<ItemsRepeater Items="{Binding ChannelCollection}">
<ItemsRepeater.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Value, Mode=TwoWay}">
<CheckBox.Content>
<MultiBinding Converter="{StaticResource ElementIndexConverter}">
<MultiBinding.Bindings>
<Binding Path="$parent[ItemsRepeater].DataContext.ChannelCollection"/>
<Binding Path="."/>
</MultiBinding.Bindings>
</MultiBinding>
</CheckBox.Content>
</CheckBox>
</StackPanel>
</DataTemplate>
</ItemsRepeater.ItemTemplate>
</ItemsRepeater>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.