这是在不违反 MVVM 的情况下执行此操作的方法。
<ListBox DockPanel.Dock="Top"
ItemsSource="{Binding Books, Mode=OneWay}"
SelectedItem="{Binding CurrentBook, Mode=TwoWay}"
SelectedIndex="{Binding SelectedIndex}"
SelectionChanged="ListBox_SelectionChanged"
/>
后面的代码:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var lb = (ListBox)sender;
lb.ScrollIntoView(lb.SelectedItem);
}
这是一种更体面的方式。对于这种事情使用背后的代码并没有错误,但是如果像这样的某些行为将在不同的视图中多次使用,则使用附加属性比复制和粘贴更方便事件处理程序。此外,它现在可以在DataTemplate 等上下文中使用,其中可能没有代码。
前面还有一些代码,但您可以轻松地将附加属性添加到项目中的任何ListBox。
public static class ListBoxExtensions
{
#region ListBoxExtensions.KeepSelectedItemVisible Attached Property
public static bool GetKeepSelectedItemVisible(ListBox lb)
{
return (bool)lb.GetValue(KeepSelectedItemVisibleProperty);
}
public static void SetKeepSelectedItemVisible(ListBox lb, bool value)
{
lb.SetValue(KeepSelectedItemVisibleProperty, value);
}
public static readonly DependencyProperty KeepSelectedItemVisibleProperty =
DependencyProperty.RegisterAttached("KeepSelectedItemVisible", typeof(bool), typeof(ListBoxExtensions),
new PropertyMetadata(false, KeepSelectedItemVisible_PropertyChanged));
private static void KeepSelectedItemVisible_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var lb = (ListBox)d;
if ((bool)e.NewValue)
{
lb.SelectionChanged += ListBox_SelectionChanged;
ScrollSelectedItemIntoView(lb);
}
else
{
lb.SelectionChanged -= ListBox_SelectionChanged;
}
}
private static void ScrollSelectedItemIntoView(ListBox lb)
{
lb.ScrollIntoView(lb.SelectedItem);
}
private static void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ScrollSelectedItemIntoView((ListBox)sender);
}
#endregion ListBoxExtensions.KeepSelectedItemVisible Attached Property
}
XAML:
<ListBox DockPanel.Dock="Top"
ItemsSource="{Binding Books, Mode=OneWay}"
SelectedItem="{Binding CurrentBook, Mode=TwoWay}"
SelectedIndex="{Binding SelectedIndex}"
local:ListBoxExtensions.KeepSelectedItemVisible="True"
/>