根据ListBoxItem在ListBox中的索引来设置其样式 [英] Styling a ListBoxItem depending on its index in the ListBox
问题描述
如果SomeProperty的值为10,我想更改ListBox中第一项的边距,而没有代码隐藏. 这是我到目前为止的内容:
I want to change the margin of the first item in the ListBox if SomeProperty value is 10, without code-behind. This is what I have so far:
<ListBox x:Class="Windows.CustomList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Windows"
mc:Ignorable="d" x:Name="MyList"
d:DesignHeight="300" d:DesignWidth="300">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=SomeProperty}" Value="10"/>
<Condition Binding="{Binding Path=Items.Count, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}}" Value="1" />
</MultiDataTrigger.Conditions>
<Setter Property="Margin">
<Setter.Value>
<Thickness Left="500"/>
</Setter.Value>
</Setter>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<local:ListBoxItemCustomTemplate/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
当我尝试这种方法时,我得到:
When I try this approach I get:
System.Windows.Data错误:4:找不到参考'RelativeSource FindAncestor,AncestorType ='ListBox',AncestorLevel ='1''的绑定源. BindingExpression:Path = Items.Count; DataItem = null;目标元素是'ListBox'(Name =''); target属性为"NoTarget"(类型为"Object")
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='ListBox', AncestorLevel='1''. BindingExpression:Path=Items.Count; DataItem=null; target element is 'ListBox' (Name=''); target property is 'NoTarget' (type 'Object')
如果我只有第一个条件,它将正确应用边距. 我尝试过的另一种方法是使用ElementName:
If I have only the first condition, it applies the margin properly. Another way I tried was by using the ElementName:
这种方法不会产生任何错误,但也不起作用.
This approach doesn't give any error but it's not working either.
任何帮助将不胜感激.
推荐答案
See AlternationIndex
. (You can use a very high AlternationCount
to ensure that only the first item has index 0
and trigger on that).
这有点滥用,更干净的方法是值转换器/多值转换器,它通过listBox.Items.IndexOf(currentItem)
之类的方法获取索引.
This is a bit abusive, a cleaner method would be a value converter / multi value converter, that gets the index via something like listBox.Items.IndexOf(currentItem)
.
这篇关于根据ListBoxItem在ListBox中的索引来设置其样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!