gpt4 book ai didi

c# - 在组合框中显示项目索引

转载 作者:行者123 更新时间:2023-12-03 11:00:04 25 4
gpt4 key购买 nike

我有一个组合绑定(bind)到项目源。我想将项目的索引显示为 DisplayMemberPath 而不是绑定(bind)对象的任何属性。

我怎样才能达到同样的效果。

最佳答案

您可以使用 MultiValueConverter 执行此操作,方法是传入集合和当前项目,然后返回项目集合中项目的索引:

public class ItemToIndexConverter : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var itemCollection = value[0] as ItemCollection;
var item = value[1] as Item;

return itemCollection.IndexOf(item);
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Xaml
<ComboBox Name="MainComboBox" ItemsSource="{Binding ComboSourceItems}">
<ComboBox.Resources>
<cvtr:ItemToIndexConverter x:Key="ItemToIndexConverter" />
</ComboBox.Resources>
<ComboBox.ItemTemplate>
<DataTemplate DataType="{x:Type vm:Item}">
<Label>
<Label.Content>
<MultiBinding Converter="{StaticResource ItemToIndexConverter}">
<Binding Path="Items" ElementName="MainComboBox" />
<Binding />
</MultiBinding>
</Label.Content>
</Label>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

希望这可以帮助。

关于c# - 在组合框中显示项目索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15225834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com