Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 刷新ItemsSource时,GridView将丢失SelectedIndex值_Wpf_Listview - Fatal编程技术网

Wpf 刷新ItemsSource时,GridView将丢失SelectedIndex值

Wpf 刷新ItemsSource时,GridView将丢失SelectedIndex值,wpf,listview,Wpf,Listview,微软我认为这可能是一个错误。使用ListView GridView显示单个记录 当然,向下箭头键在ListViewItems中导航。这就是我所期望的行为。在XAML中,ItemsSource和SelectedIndex是绑定的。我想要的行为是使用左右箭头键导航到下一条和上一条记录 实现这一点的方法是处理ListView PreviewKeyDown事件。我遇到的问题是,当ItemSource刷新时,SelectedIndex被重置为-1,我希望它保持在旧的SelectedIndex上。因此,我必

微软我认为这可能是一个错误。使用ListView GridView显示单个记录

当然,向下箭头键在ListViewItems中导航。这就是我所期望的行为。在XAML中,ItemsSource和SelectedIndex是绑定的。我想要的行为是使用左右箭头键导航到下一条和上一条记录

实现这一点的方法是处理ListView PreviewKeyDown事件。我遇到的问题是,当ItemSource刷新时,SelectedIndex被重置为-1,我希望它保持在旧的SelectedIndex上。因此,我必须手动重置SelectedIndex,如下所示

这是我的问题:在左箭头或右箭头键之后,且仅在其直接之后,上下键不会传递SelectedIndex的正确值

例如,SelectedIndex=4,然后向右箭头,然后向下键,传递给SelectedIndex的值为0,传递的值应为4。ListView直观地显示在SelectedIndex 4上,因此它好像知道SelectedIndex是4,但它也不知道。如果我不更改项目来源,则上下箭头键工作正常。我尝试了KeyDown和KeyUp事件,但在这种情况下,这些事件在上述失败条件下根本不会触发

WPF4.0VisualStudio2010

private void lvCurDocFields_PreviewKeyDown(object sender, KeyEventArgs e)
{
    Debug.WriteLine("lvCurDocFields_PreviewKeyDown " + e.Key.ToString());
    e.Handled = false;
    Int32 lastIndex;
    switch (e.Key)  // e.KeyCode
    {
        case Key.Right:
            lastIndex = lvCurDocFields.SelectedIndex;
            App.StaticGabeLib.Search.SelectedDocIndex++;
            if (lvCurDocFields.SelectedIndex != lastIndex)
            {
                lvCurDocFields.SelectedIndex = lastIndex;
            }
            e.Handled = true;
            break;
        case Key.Left:
            lastIndex = lvCurDocFields.SelectedIndex;
            App.StaticGabeLib.Search.SelectedDocIndex--;
            if (lvCurDocFields.SelectedIndex != lastIndex)
            {
                lvCurDocFields.SelectedIndex = lastIndex;
            }
            e.Handled = true;
            break;
    }
    base.OnPreviewKeyDown(e);
}

通常,我存储对所选项目的引用,更新列表,然后重新选择它。如果从列表中插入或删除内容,ListIndex不是维护选择的可靠方法

if(MyListControl.Items.Contains(PreviouslySelectedItem)) MyListControl.SelectedItem = PreviouslySelectedItem;

我认为这不会起作用,因为从技术上讲,它不是同一个SelectedItem,而是同一个SelectedIndex。新记录有相同的条目(ListItems),但列表项有新的值——我只是在移动一个集合。基本上,我认为我在做你建议的事情,但使用SelectedIndex。我错过了什么?注意,当我导航到新记录时,它确实给出了正确的答案。它中断的地方是直接在新记录之后通过向上或向下箭头键移动到新的ListItem。