如何绑定 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.
理想情况下,我们应该有
Ideally, we would have
<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
属性,但无论如何-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屋!
查看全文