ListBox ScrollIntoView from XAML

本文关键字:XAML from ScrollIntoView ListBox | 更新日期: 2023-09-27 17:57:44

我正在使用情节提要为ListBox的SelectedIndex设置动画。

    <Storyboard x:Key="FlipBook" RepeatBehavior="Forever">
        <Int32AnimationUsingKeyFrames Storyboard.TargetProperty="(Selector.SelectedIndex)" Storyboard.TargetName="FlipBookView">
            <EasingInt32KeyFrame KeyTime="0" Value="0"/>
            <EasingInt32KeyFrame KeyTime="0:0:1" Value="1"/>
            <EasingInt32KeyFrame KeyTime="0:0:2" Value="0"/>
        </Int32AnimationUsingKeyFrames>
    </Storyboard>

当SelectedIndex更改时,我希望ListBox自动(并立即)滚动到该项。

我相信ListBox.ScrollIntoView会做我想要的事情,但我需要它在SelectedIndex更改时自动触发。

这可能吗?

ListBox ScrollIntoView from XAML

我要做的是使用System.Windows.Interactivity创建Behaviors。您必须在项目中手动引用它。

给定一个不公开SelectedItems的控件,例如(ListBox,DataGrid)

你可以创建一个类似的行为类

public class ListBoxSelectedItemsBehavior : Behavior<ListBox>
{
    protected override void OnAttached()
    {
        AssociatedObject.SelectionChanged += AssociatedObjectSelectionChanged;
    }
    protected override void OnDetaching()
    {
        AssociatedObject.SelectionChanged -= AssociatedObjectSelectionChanged;
    }
    void AssociatedObjectSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // Assuming your selection mode is single.
        AssociatedObject.ScrollIntoView(e.AddedItems[0]);
    }

在你的XAML上,我会这样做Binding,其中ixmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"behaviorsBehavior类的名称空间

<ListBox>
 <i:Interaction.Behaviors>
    <behaviors:ListBoxSelectedItemsBehavior/>
 </i:Interaction.Behaviors>
</ListBox>

假设ListBoxDataContextViewModel中具有SelectedItems属性,则它将自动更新SelectedItems。您已经封装了从View订阅的event,即

<ListBox SelectionChanged="ListBox_SelectionChanged"/>

如果需要,可以将Behavior类更改为DataGrid类型。