How can I bind against the Index of a ListBoxItem

自闭症网瘾萝莉.ら 提交于 2019-12-20 06:27:34

问题


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.

Any taker?


回答1:


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}}" />
    <!-- ... -->


来源:https://stackoverflow.com/questions/3843829/how-can-i-bind-against-the-index-of-a-listboxitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!