如何绑定ListBoxItem的索引 [英] How can I bind against the Index of a ListBoxItem
本文介绍了如何绑定ListBoxItem的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将列表框项目的z索引绑定到其索引。
I'd like to bind the z index of list box items to their index.
理想情况下,我们将有
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Panel.ZIndex"
Value="{Binding RelativeSource={RelativeSource Self}, Path=-Index}" />
<!-- ... -->
但是,列表框项目没有索引属性。
However, the list box item does not have an index property.
我可以想到一些疯狂的解决方案,但没有简单和优雅。
I can think of a number of crazy solutions but nothing simple and elegant.
任何人?
推荐答案
没有索引
属性,但无论如何,-Index不会是有效的路径...您仍然需要一个转换器来否定该值。所以你可以做的是创建一个转换器,从 ItemContainerGenerator中获取索引
There is no Index
property, but anyway "-Index" wouldn't be a valid path... you would still need a converter to negate the value. So what you can do is create a converter that retrieves the index from the ItemContainerGenerator
public class ItemContainerToZIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var itemContainer = (DependencyObject)value;
var itemsControl = FindAncestor<ItemsControl>(itemContainer);
int index = itemsControl.ItemContainerGenerator.IndexFromContainer(itemContainer);
return -index;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
public static T FindAncestor<T>(this DependencyObject obj) where T : DependencyObject
{
var tmp = VisualTreeHelper.GetParent(obj);
while (tmp != null && !(tmp is T))
{
tmp = VisualTreeHelper.GetParent(tmp);
}
return (T)tmp;
}
}
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Panel.ZIndex"
Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource zIndexConverter}}" />
<!-- ... -->
这篇关于如何绑定ListBoxItem的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文