简体   繁体   中英

ListBox ScrollIntoView from XAML

I am animating the SelectedIndex of a ListBox using a StoryBoard.

    <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>

When the SelectedIndex changes, I would like the ListBox to automatically (and instantly) scroll to that item.

I believe ListBox. ScrollIntoView will do exactly what I want, but I need it to be triggered automatically when the SelectedIndex changes.

Is this possible?

What I would do is create Behaviors using System.Windows.Interactivity . You would have to reference it manually in your project.

Given a control which doesn't expose SelectedItems eg, (ListBox, DataGrid)

You can create a behavior class something like this

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]);
    }

And on your XAML I would do the Binding like this where i is xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" and behaviors is the namespace of your Behavior class

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

Assuming that your DataContext for the ListBox has the SelectedItems property in the ViewModel then it will automatically update the SelectedItems . You have encapsulated the event subscribing from the View ie,

<ListBox SelectionChanged="ListBox_SelectionChanged"/>

You can change the Behavior class to be of type DataGrid if you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM