Joe*_*ant 5 wpf listbox wrappanel
我试图实现相当于WinForms ListView的View属性设置为View.List.在视觉上,以下工作正常.我的文件名Listbox从上到下,然后换行到新列.
这是我正在使用的基本XAML:
<ListBox Name="thelist"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True"
Orientation="Vertical" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
但是,默认箭头键导航不会换行.如果选择了列中的最后一项,则按向下箭头不会转到下一列的第一项.
我尝试KeyDown像这样处理事件:
private void thelist_KeyDown( object sender, KeyEventArgs e ) {
if ( object.ReferenceEquals( sender, thelist ) ) {
if ( e.Key == Key.Down ) {
e.Handled = true;
thelist.Items.MoveCurrentToNext();
}
if ( e.Key == Key.Up ) {
e.Handled = true;
thelist.Items.MoveCurrentToPrevious();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生我想要的最后一列到下一列的行为,但在左右箭头处理中也会产生奇怪的现象.每当使用向上/向下箭头从一列包裹到下一个/上一个列时,单个后续使用左或右箭头键将选择移动到刚好在换行之前选择的项目的左侧或右侧.
假设列表填充字符串"0001"到"0100",每列10个字符串.如果我使用向下箭头键从"0010"变为"0011",则按右箭头键,选择移动到"0020",就在"0010"的右侧.如果选择"0011"并且我使用向上箭头键将选择移动到"0010",则按下右箭头键将选择移动到"0021"("0011"的右侧,并按下左侧箭头键将选择移动到"0001".
任何帮助实现所需的列包裹布局和箭头键导航将不胜感激.
(编辑转到我自己的答案,因为它在技术上是一个答案.)
事实证明,当我处理KeyDown事件时,选择会更改为正确的项目,但重点是旧项目.
这是更新的KeyDown事件处理程序.由于绑定,Items集合返回我的实际项而不是ListBoxItems,所以我必须在接近结束时进行调用以获得ListBoxItem我需要调用的实际Focus()内容.从最后一项第一,反之亦然包装可以通过交换的呼叫来实现MoveCurrentToLast()和MoveCurrentToFirst().
private void thelist_KeyDown( object sender, KeyEventArgs e ) {
if ( object.ReferenceEquals( sender, thelist ) ) {
if ( thelist.Items.Count > 0 ) {
switch ( e.Key ) {
case Key.Down:
if ( !thelist.Items.MoveCurrentToNext() ) {
thelist.Items.MoveCurrentToLast();
}
break;
case Key.Up:
if ( !thelist.Items.MoveCurrentToPrevious() ) {
thelist.Items.MoveCurrentToFirst();
}
break;
default:
return;
}
e.Handled = true;
ListBoxItem lbi = (ListBoxItem) thelist.ItemContainerGenerator.ContainerFromItem( thelist.SelectedItem );
lbi.Focus();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您应该可以在没有事件侦听器的情况下使用 KeyboardNavigation.DirectionalNavigation 做到这一点,例如
<ListBox Name="thelist"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
KeyboardNavigation.DirectionalNavigation="Cycle">
Run Code Online (Sandbox Code Playgroud)