根据其在 ListBox 中的索引设置 ListBoxItem 的样式

Ari*_*ris 3 wpf xaml listbox listboxitem multidatatrigger

如果 SomeProperty 值为 10,我想更改 ListBox 中第一项的边距,而无需代码隐藏。这是我到目前为止:

<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>
Run Code Online (Sandbox Code Playgroud)

当我尝试这种方法时,我得到:

System.Windows.Data 错误:4:无法找到引用“RelativeSource FindAncestor、AncestorType='ListBox'、AncestorLevel='1'”的绑定源。BindingExpression:Path=Items.Count; 数据项=空;目标元素是 'ListBox' (Name=''); 目标属性是“NoTarget”(类型“Object”)

如果我只有第一个条件,它会正确应用边距。我尝试的另一种方法是使用 ElementName:

这种方法不会出现任何错误,但也不起作用。

任何帮助将非常感激。

H.B*_*.B. 5

AlternationIndex。(您可以使用非常高的值AlternationCount来确保只有第一项具有索引0和触发器)。

这有点滥用,更简洁的方法是值转换器/多值转换器,它通过类似listBox.Items.IndexOf(currentItem).

  • 而不是使用任意高的`AlternationCount`,您可以将其绑定到项目的计数,以便每个项目的 AlternationIndex 是唯一的。`AlternationCount="{Binding Items.Count, RelativeSource={RelativeSource Self}}"` (3认同)