【发布时间】:2011-08-16 16:22:09
【问题描述】:
我正在为给定 ListBox 的 ListBoxItems 使用 ControlTemplate。 ControlTemplate 在 Style 中定义,并包含一个 Rectangle,其 Visibility 需要根据 AlternationIndex 进行切换。虽然我看到了如何使用 AlternationIndex 直接控制 ListBoxItem 的背景,但我不确定如何使用触发器来引用控件模板中的命名项。任何意见表示赞赏:
XAML 摘录:
<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Grid Height="84" Width="700">
<!--
TURN ME ON FOR EVERY EVEN NUMBERED LIST ITEM
-->
<Rectangle x:Name="_listItemBg" Width="700" Height="83" Opacity="0.12">
...
我尝试了以下方法,但无济于事。正确的 XAML 语法避开了我:
<ControlTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Rectangle.Visibility" TargetName="_listItemBg" Value="Hidden" />
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Rectangle.Visibility" TargetName="_listItemBg" Value="Visible" />
</Trigger>
...
【问题讨论】:
-
这可能是因为您在 Rectangle 的定义中明确设置了 Visibility="Visible"。尝试删除它并让样式设置器处理它。
-
谢谢,但似乎不是这样。我现在更新了 Trigger 以包含 TargetName 属性,但是虽然我在输出中没有看到绑定错误,但它似乎没有工作。上面的 Trigger 和 Rectangle 已更新以反映这一最新尝试。
-
根据您的评论,Matt,似乎我需要两个互补的触发器 - 一个隐藏矩形,一个显示它。我更新了 XAML。可悲的是,这也行不通。
-
是的,我还没有看到像这样在 ControlTemplate 中使用 AlternationIndex - 仅在样式中。也许您可以在 Rectangle 上设置样式并使用 RelativeSource 绑定来查找 AlternationIndex 的当前值?