【问题标题】:How can I set the currently focussed item in a System.Windows.Controls.ListView?如何在 System.Windows.Controls.ListView 中设置当前聚焦的项目?
【发布时间】:2016-07-12 15:07:06
【问题描述】:

我在用户控件中有一个 ListView:

<ListView ...
          ItemsSource="{Binding Path=MyItemsSource}"
          SelectedItem="{Binding Path=SelectedItem}"
          SelectionMode="{Binding Path=SelectionMode}"
          >
    <ListView.View>
        <GridView>
            ...
        </GridView>
    </ListView.View>
</ListView>

我在视图模型中有代码以编程方式设置 ListView 的 SelectedItem。这是通过在视图模型中设置 SelectedItem 属性来实现的。

我发现当我的代码将 SelectedItem 属性设置为特定列表项时,具有键盘焦点的项不会随之更改。如果我更改 SelectedItem 属性然后按向上箭头键,则新选择的项目是之前选择的项目上方的项目(因为该项目仍然具有焦点),而不是新选择的项目上方的项目.

this question 中选择的答案建议使用如下代码:

ListViewItem item = myListView.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;

但是,该解决方案无法为我编译。我收到以下错误:

CS0039:无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换将类型“System.Windows.DependencyObject”转换为“System.Windows.Forms.ListViewItem”。

我已经解决了this question 中描述的一个问题,该问题与在以编程方式设置所选项目后,当用户按住 shift 单击时,错误的列表项被用作多选的起点。这可以通过在设置所选项目之前和之后更改 SelectionMode 来解决:

private MyItemType _selectedItem;
public MyItemType SelectedItem
{
    get
    {
        return _selectedItem;
    }
    set // Use SetSelectedItemInternal() internally!
    {
        SetProperty(ref _selectedItem, value);
    }
}

/// <summary>
/// Use this when programatically setting the SelectedItem. This method incorporates a workaround for a bug (?) in WPF
/// that causes confusing behaviour when shift-selecting items in the list after the SelectedItem is programatically changed.
/// See https://stackoverflow.com/questions/11950021/wpf-listview-shift-selecting-multiple-items-wrong-start-item
/// </summary>
private void SetSelectedItemInternal(MyItemType newSelectedItem, bool scrollToNewItem = true)
{
    SelectionMode = SelectionMode.Single;
    SelectedItem = newSelectedItem;
    SelectionMode = SelectionMode.Extended;

    if (scrollToNewItem)
    {
        ScrollToListItem(MyItemsSource.IndexOf(newSelectedItem));
    }
}

【问题讨论】:

  • 您的问题隐含在标签和您拥有 XAML 的事实中。
  • 细心的读者很清楚问题是关于哪个 ListView 和难以忽视之间是有区别的。
  • 嗯,确实很难忽视,winforms 中没有 XAML。此外,很多回答问题的人都有一些他们喜欢的标签,所以他们甚至可能看不到 winforms 的问题。如果他们同时浏览这两个标签,如果不明显,他们可能会确保检查它是关于什么的。

标签: wpf xaml mvvm data-binding focus


【解决方案1】:

CS0039:无法将类型“System.Windows.DependencyObject”转换为“System.Windows.Forms.ListViewItem”

您的代码中有错误的using 语句(引用Windows 窗体命名空间)。此外,只需转换为DependencyObject,因为这显然是您列出的内容。然后您应该能够专注于这一点,尽管如果新选定的项目不在屏幕上,UI 虚拟化会阻止这一点。

【讨论】:

  • 我不知道你是如何从这么少的信息中识别出来的,但你猜对了。
  • 异常告诉你所有你需要知道的,真的。
猜你喜欢
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多