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>