我有一个使用数据模板的列表框。我需要的是在选择项目后我想缩小列表框本身,而不是里面的列表项。我已经在 selector.selected 和 unselected 上尝试了事件触发器,但它没有触发。我还在数据模板上放了一个数据触发器,但我无法从这里访问列表框。有任何想法吗?
2 回答
这是一个稍微间接的解决方案,但是...您可以通过在 ListBox 本身上放置一个 DataTrigger 并绑定到 SelectedItems.Count 来处理这个问题。您需要将 ListBox 默认设置为“较小”的外观。然后触发器将检查 SelectedItems.Count 是否为 0,如果是,则必须使 ListBox变大。在下面的示例中,为了简单起见,我设置了 ListBox.Background,但您应该能够对其进行调整以在 LayoutTransform 或 RenderTransform 或 Width/Height 或您用来“缩小” ListBox 的任何内容上进行操作:
<ListBox.Style>
<Style TargetType="ListBox">
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource Self}}" Value="0">
<Setter Property="Background" Value="Orange" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Style>
Obviously this will shrink (or, in my simplified example, turn white) the entire ListBox when anything is selected. 要使选定的 ListBoxItem 保持完整大小,请使用 ListBox.ItemContainerStyle。在这种情况下,您可以触发 IsSelected,并应用合适的设置器来反转“收缩”转换——例如应用负边距或反向 ScaleTransform。(一个普通的触发器可以做到这一点。)
首先,要挂钩的正确事件是SelectionChanged
not Selected
,其次,您可以Storyboard
在窗口级别使用 a :
Storyboard
: _
<Storyboard x:Key="Storyboard1">
<DoubleAnimationUsingKeyFrames
BeginTime="00:00:00"
Storyboard.TargetName="grid"
Storyboard.TargetProperty="(FrameworkElement.Height)">
<SplineDoubleKeyFrame KeyTime="00:00:00.5000000" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
窗口触发器:
<Window.Triggers>
<EventTrigger RoutedEvent="Selector.SelectionChanged" SourceName="listBox">
<BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
</EventTrigger>
</Window.Triggers>
还有ListBox
(带有一些装饰效果):
<Border
BorderThickness="2"
CornerRadius="3"
BorderBrush="#FF000000"
Padding="3"
VerticalAlignment="Top">
<Grid Height="200" x:Name="grid">
<ListBox x:Name="listBox" Height="200">
<ListBoxItem Content="ListBoxItem"/>
<ListBoxItem Content="ListBoxItem"/>
<ListBoxItem Content="ListBoxItem"/>
<ListBoxItem Content="ListBoxItem"/>
</ListBox>
</Grid>
</Border>