如何以编程方式选择列表视图项目

时间:2018-10-07 13:07:58

标签: c# listview uwp

我正在制作图书馆管理软件。当用户单击一本书时,我想显示有关这本书的完整信息。书籍类型的属性之一是标签。因为一本书可能有很多标签,所以我决定使用列表视图来显示标签。

我想在列表视图中选择标签。我该怎么做?我找到了this question。接受的答案表明,使用的方法ListView.Select()不幸地不存在。另外,ListView.Items[0].Selected = true;无法编译。这是错误:

  

错误CS1061'对象'不包含'选定对象'的定义,并且找不到可以接受的扩展方法'选定对象'接受类型为'对象'的第一个参数(您是否缺少using指令或程序集引用?)

编辑:有人要求输入代码。在这里。

这是列表视图:

<ListView x:Name="TagsListView"
                  SelectionMode="Multiple"
                  ItemsSource="{x:Bind Tags}"
                  Grid.Row="4"
                  Grid.Column="1"/>

这是背后的代码:

public sealed partial class BookInfo_View : Page
{
    //don't worry about DataAccess. 
    private Book book = new Book();
    private List<string> Tags = DataAccess.GetTags();

    public BookInfo_View()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        book = (Book)e.Parameter;

        //dont worry about how this works. This line of code gives me the tags
        string[] selectedTags = book.Tags.Split(';', System.StringSplitOptions.RemoveEmptyEntries);

        //here i want to select the selected tags
    }
}

这是书本课:

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string Publisher { get; set; }
    public string ISBN { get; set; }

    public int Quantity { get; set; }

    public string CoverImageLocation { get; set; }

    public string Tags { get; set; }
}

编辑:我觉得你们不明白这个问题。问题是

ListView.Items[0].Selected = true;

上面的代码行无法编译!它给出了上面提到的错误

3 个答案:

答案 0 :(得分:1)

当您更新ListView中的OnNavigatedTo个选定项时,您的ListView可能当时未用数据初始化,而是尝试按如下所示更新页面Loaded中的ListView

public sealed partial class BookInfo_View : Page
{
    //don't worry about DataAccess. 
    private Book book = new Book();
    private List<string> Tags = DataAccess.GetTags();
    private string[] selectedTags;

    public BookInfo_View()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        book = (Book)e.Parameter;

        //dont worry about how this works. This line of code gives me the tags
        selectedTags = book.Tags.Split(';', System.StringSplitOptions.RemoveEmptyEntries);

        //here i want to select the selected tags
        this.Loaded += OnPageLoaded;
    }

    private void OnPageLoaded(object sender, RoutedEventArgs e)
    {
       foreach (string selectedTag in selectedTags)
       {
         TagsListView.SelectedItems.Add(selectedTag);
       }
    }
}

答案 1 :(得分:0)

ListView.Select()仅激活控件(将焦点设置给它),并且不选择其项目,因此它不是您想要的。

但是您已经提到的这个问题的答案是:

ListView1.Items[0].Selected = true;

但是,您应该使用存在ListView实例的名称属性,而不要使用ListView本身。如果您尚未重命名,则其名称应该类似于listView1

答案 2 :(得分:0)

基于this,我认为您应该将标签添加到TagsListView.SelectedItems

相关问题