簡體   English   中英

如何以編程方式選擇列表視圖項目

[英]How to select a list view item programatically

我正在制作圖書館管理軟件。 當用戶單擊一本書時,我想顯示有關這本書的完整信息。 書籍類型的屬性之一是標簽。 因為一本書可能有很多標簽,所以我決定使用列表視圖來顯示標簽。

我想在列表視圖中選擇標簽。 我該怎么做? 我發現了這個問題 接受的答案說使用遺憾的是不存在的方法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;

上面的代碼行無法編譯! 它給出了上面提到的錯誤

當您更新OnNavigatedTo ListView選定項時,您的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);
       }
    }
}

ListView.Select()僅激活控件(將焦點設置給它),並且不選擇其項目,因此它不是您想要的。

但是您已經提到的這個是您問題的答案:

ListView1.Items[0].Selected = true;

但是,您應該使用存在ListView實例的名稱屬性,而不要使用ListView本身。 如果尚未重命名,則它應該類似於listView1

基於 ,我認為您應該將標簽添加到TagsListView.SelectedItems

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM