gpt4 book ai didi

WPF:XAML 中的绑定(bind)列表 - 项目如何知道其在列表中的位置?

转载 作者:行者123 更新时间:2023-12-04 12:14:15 30 4
gpt4 key购买 nike

给定以下具有类似 ListControl 行为的 XAML 代码:

    <StackPanel>
<ItemsControl Name="_listbox" ItemsSource="{Binding ElementName=_userControl, Path=DataContext}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel>
...
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>

由于列表可能很长(100-200 个项目),并且项目看起来相似,我认为如果每个项目都显示它们在列表中的位置,那么在滚动过程中对用户会有帮助。 模板中的项目如何知道自己在列表中的位置?

最佳答案

这是一个黑客解决方案。我们可以将值转换与 DataBinding 一起使用。所以第一步是声明我们的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>

注:在此示例中,项目将从 0(零)开始编号,您可以在 Convert 方法中通过将 1 添加到结果来更改它。

希望这可以帮助...

关于WPF:XAML 中的绑定(bind)列表 - 项目如何知道其在列表中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3607368/

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