我想将列表框项的z索引绑定到它们的索引。
理想情况下,我们会
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Panel.ZIndex"
Value="{Binding RelativeSource={RelativeSource Self}, Path=-Index}" />
<!-- ... -->
但是,列表框项目没有索引属性。
我可以想到一些疯狂的解决方案,但没有简单和优雅。
任何接受者?
答案 0 :(得分:2)
没有Index
属性,但无论如何“-Index”不是有效路径......你仍然需要一个转换器来否定该值。所以你可以做的是创建一个从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}}" />
<!-- ... -->