我想将一个项目添加到列表视图,然后选择并滚动到它。但滚动不会移动到该项目。当我尝试添加多个项目时,滚动移动到一个项目,但这不是最后添加的项目。看来使用绑定添加项目后,listviewItem不会立即生成。
我尝试添加一个项目,然后选择它(使用绑定)并滚动到上一个选定的项目。但这不起作用,因为所选项目的数量将为零。
if (lV.SelectedItems.Count > 0)
{
// do it here (but it will not run because lV.SelectedItems.Count is zero)
}
我还尝试从绑定中获取项目,但返回值将为空。
ListViewItem item = (ListViewItem)lV.ItemContainerGenerator.ContainerFromItem(lastItem);
//but item will be null
请注意,我还根据建议使用here使用了VirtualizingPanel.IsVirtualizing="False"
。
通过绑定选择效果很好,我考虑了绑定焦点,但是IsFocused
属性只允许不设置。那我该怎么办呢?
================================================ ==========
编辑:我在xaml中有以下代码:
<local:PrefectListView x:Name="lV"
AllowDrop="true"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
VirtualizingPanel.IsVirtualizing="False"
SelectionChanged="lVImage_SelectionChanged"
PreviewKeyDown="lV_PreviewKeyDown"
Drop="lV_Drop"
DragEnter="lV_DragEnter"
ItemDragsAndDropedToPC="lV_ItemDragsAndDropedToPC" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="80" Height="120" >
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="{Binding Thumbnail}" Margin="5"/>
<TextBlock Grid.Row="1" Text="{Binding Name}" Margin="5,0,5,5" HorizontalAlignment="Center" VerticalAlignment="Top"
TextWrapping="Wrap" TextTrimming="CharacterEllipsis"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="MouseDoubleClick" Handler="lVItem_MouseDoubleClick"/>
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
<Setter Property="Margin" Value="5,5,2,2"/>
</Style>
</ListView.ItemContainerStyle>
</local:PrefectListView>
在cs中,创建项目后,我将其添加到_navigationSources
,然后使用以下代码选择并滚动到它:
private void SelectItems(bool clearPreviousSelecteds, bool focus, NavigationPanItemRow[] rows)
{
//force to run it on UI thread
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
//check arguments
if (rows == null) { throw new ArgumentNullException("rows"); }
//
for (int i = 0; i < rows.Length; i++)
{
if (rows[i] == null)
{ throw new ArgumentException("Atleast one of members is null", "rows"); }
}
//variables
NavigationPanItemRow lastItem = null;
//clear all selected
if (clearPreviousSelecteds)
{
_navigationSources.UnSelectAll();
}
//select
for (int i = 0; i < rows.Length; i++)
{
rows[i].IsSelected = true;
lastItem = rows[i];
}
//focus (I use it )
if (focus && lastItem != null)
{
lV.Focus();
ListViewItem it = (ListViewItem)lV.ItemContainerGenerator.ContainerFromItem(lastItem);
lV.ScrollIntoView(it);
}
//focus (also it)
if (focus && lV.SelectedItems.Count > 0)
{
lV.Focus();
((ListViewItem)lV.ItemContainerGenerator.ContainerFromItem(lV.SelectedItems[lV.SelectedItems.Count - 1])).Focus();
}
}));
}
注意:如果我在焦点部分之前添加一个消息框,这会花一些时间,因此代码效果很好。