1

Как сделать, чтобы когда пропадет фокус с ListView, выделенный элемент был виден пользователю? То есть, чтобы ScrollViewer прокрутился к выделенному элементу в ListView.

            <ScrollViewer Grid.Column="1"  Width="200" HorizontalAlignment="Right" 
                          HorizontalScrollBarVisibility="Hidden"
                          Mouse.PreviewMouseWheel="ScrollViewer_PreviewMouseWheel"
                          VerticalScrollBarVisibility="Visible">
            <ListView ItemsSource="{Binding CustomControls, IsAsync=True}"  
                      SelectedIndex="{Binding CurrentIndex, Mode=TwoWay}" BorderThickness="0">
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical"></StackPanel>
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>
            </ListView>
        </ScrollViewer>

2 ответа 2

0
public static class ListViewItemBehavior
    {

        public static bool GetIsBroughtIntoViewWhenSelected(ListViewItem listBoxItem)
        {
            return (bool) listBoxItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);
        }


        public static void SetIsBroughtIntoViewWhenSelected(ListViewItem listBoxItem, bool value)
        {
            listBoxItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);
        }

        public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty = 
            DependencyProperty.RegisterAttached(
            "IsBroughtIntoViewWhenSelected", typeof(bool), typeof(ListViewItemBehavior), 
            new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));


        private static void OnIsBroughtIntoViewWhenSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            var item = depObj as ListViewItem;
            if (item == null)
                return;

            if (e.NewValue is bool == false)
                return;

            if ((bool)e.NewValue)
                item.Selected += OnListBoxItemSelected;
            else
                item.Selected -= OnListBoxItemSelected;
        }

        private static void OnListBoxItemSelected(object sender, RoutedEventArgs e)
        {
            if (!ReferenceEquals(sender, e.OriginalSource))
                return;
            var item = e.OriginalSource as ListViewItem;
            item?.BringIntoView();
        }
    }

Подключаем xmlns

xmlns:util="clr-namespace:YourNamespaceHere.Classes"

Создаем стиль

    <Controls:MetroWindow.Resources>
                    <Style x:Key="ListBoxItemContainerStyle" TargetType="{x:Type ListBoxItem}"
            BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <Setter Property="myControl:ListViewItemBehavior.IsBroughtIntoViewWhenSelected" Value="true"/>
            </Style>
   </Controls:MetroWindow.Resources>

Используем стиль

ListView ItemsSource="{Binding CustomControls, IsAsync=True}"  ItemContainerStyle="{StaticResource ListBoxItemContainerStyle}"
                           SelectedIndex="{Binding CurrentIndex, Mode=TwoWay}" BorderThickness="0">
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical"></StackPanel>
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>
            </ListView>
0

Попробуйте:

listview1.ScrollIntoView(listView1.SelectedItem);

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.