1

I am using a SelectionChanged event in ListView1, which changes a string: "dr.CustomBackgroundColor". That string is used to find the index and change the selection in a target ListView: "SetColorListView". Which works as expected!

But the Selection in "SetColorListView" does not "jump" into view. ie. It is selected, but I have to scroll to find it...

Is there an easy way to have the SelectedItem come into view automatically?

<ListView x:Name="SetColorListView" Focusable="False"
     ItemsSource="{Binding SystemColorObservableCollection, UpdateSourceTrigger=PropertyChanged}"
     SelectedValuePath="HexValue" 
     SelectedValue="{Binding objGantChartClass.CustomBackgroundColor, Mode=TwoWay}" 
     SelectedIndex="{Binding SystemColorObservableCollectionSelectedIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="True">

SystemColorObservableCollectionSelectedIndex = SystemColorObservableCollection.IndexOf(SystemColorObservableCollection.Where(c => c.HexValue == dr.CustomBackgroundColor).FirstOrDefault());
mjordan
  • 319
  • 2
  • 22

1 Answers1

1

You can use a Behavior:

using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Jarloo.Sojurn.Behaviors
{
    public sealed class ScrollIntoViewBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.SelectionChanged += ScrollIntoView;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.SelectionChanged -= ScrollIntoView;
            base.OnDetaching();
        }

        private void ScrollIntoView(object o, SelectionChangedEventArgs e)
        {
            var b = (ListBox)o;
            if (b == null) return;
            if (b.SelectedItem == null) return;

            var item = (ListBoxItem)((ListBox)o).ItemContainerGenerator.ContainerFromItem(((ListBox)o).SelectedItem);
            if (item != null) item.BringIntoView();
        }
    }
}

Then inside your ListBox declare it like so:

<ListBox ItemsSource="{Binding Shows.View}" Background="{x:Null}"  Grid.Row="1" Grid.Column="0"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled" Style="{StaticResource NoFocusListBoxStyle}" SelectedItem="{Binding SelectedShow}">

    <i:Interaction.Behaviors>
        <behaviors:ScrollIntoViewBehavior />
    </i:Interaction.Behaviors>

    <ListBox.ItemTemplate>
        <DataTemplate>

...

You will also need the following declared as Namespaces:

xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

I grabbed this code from an open source project I have on GitHub, can view the full source here Sojurn if you need to see it in action or want more context.

Hopefully this helps!

Kelly
  • 6,992
  • 12
  • 59
  • 76