一
Behavior
是将此功能添加到控件的理想方法。下面的代码将在选择更改或调整大小后将列表框的SelectedItem滚动到视图中。
public class perListBoxHelper : Behavior<ListBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
AssociatedObject.SizeChanged += AssociatedObject_SizeChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
AssociatedObject.SizeChanged -= AssociatedObject_SizeChanged;
base.OnDetaching();
}
private static void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ScrollSelectionIntoView(sender as ListBox);
}
private static void AssociatedObject_SizeChanged(object sender, SizeChangedEventArgs e)
{
ScrollSelectionIntoView(sender as ListBox);
}
private static void ScrollSelectionIntoView(ListBox listBox)
{
if (listBox?.SelectedItem == null)
return;
Action action = () =>
{
listBox.UpdateLayout();
listBox.ScrollIntoView(listBox.SelectedItem);
};
listBox.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
}
}
用法
<ListBox ... >
<i:Interaction.Behaviors>
<vhelp:perListBoxHelper />
</i:Interaction.Behaviors>
</ListBox>
关于我最近的行为的更多讨论
blog post
.