How to pre-select multiple listview/gridview items in C#/XAML windows 8 app?

11,382

Solution 1

Finally got answer from MSDN. Thanks ForInfo

XAML page

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <ListView x:Name="listView" SelectionMode="Multiple">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBox Text="{Binding ID}" Margin="0,0,5,0"/>
                    <TextBox Text="{Binding Title}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

C#

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        LoadData();
    }
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    }
    ObservableCollection<KiwiItem> sourceColl;
    IList<KiwiItem> selectionList;
    public void LoadData()
    {
        var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");

        // Exec (1)
        using (var db = new SQLite.SQLiteConnection(dbPath))
        {
            db.DropTable<KiwiItem>();
            db.CreateTable<KiwiItem>();
            db.RunInTransaction(() =>
            {
                db.Insert(new KiwiItem() { ID = 1, Title = "MyTitle1" });
                db.Insert(new KiwiItem() { ID = 2, Title = "MyTitle2" });
                db.Insert(new KiwiItem() { ID = 3, Title = "MyTitle3" });
                db.Insert(new KiwiItem() { ID = 4, Title = "MyTitle4" });
            });
            this.sourceColl = new ObservableCollection<KiwiItem>();
            this.selectionList = new List<KiwiItem>();
            // Query the db. In practice, fill the sourceColl according to your business scenario
            foreach (KiwiItem item in db.Table<KiwiItem>())
            {
                this.sourceColl.Add(item);
                if (item.ID == 2 || item.ID == 4)
                    this.selectionList.Add(item);
            }
        }

        // Exec (2)
        this.listView.ItemsSource = this.sourceColl;
        foreach (KiwiItem item in this.selectionList)
            this.listView.SelectedItems.Add(item);
    }
}
public class KiwiItem
{
    [SQLite.AutoIncrement, SQLite.PrimaryKey]
    public int ID { get; set; }
    public string Title { get; set; }
}

Solution 2

You can use SelectedItems property.

    //
    // Summary:
    //     Gets the currently selected items.
    //
    // Returns:
    //     A collection of the currently selected items.
    public IList<object> SelectedItems { get; }

Solution 3

You can use the SelectedItems property and call SelectedItems.Add() or SelectedItems.Remove() to add/remove items from selection.

If you use ItemsSource binding on the GridView you can use the ListViewExtensions.BindableSelection attached property from the WinRT XAML Toolkit (it should work with a GridView too since it is a subclass of ListViewBase) as in the sample page.

Share:
11,382
Farhan Ghumra
Author by

Farhan Ghumra

Achievements: Microsoft Certified: Azure Developer Associate MCP: Microsoft Certified Professional (Developing ASP.NET MVC Web Applications) 2nd person to earn windows-store-apps bronze badge. 8th person to earn microsoft-metro bronze badge. 10th person to earn windows-runtime bronze badge. 18th person to earn windows-8 bronze badge. Stackoverflow Careers 2.0 : /farhanghumra LinkedIn : /farhanghumra Twitter : @FarhanGhumra Facebook : /farhan.ghumra Skype : farhan.ghumra How to pre-select multiple listview/gridview items in C#/XAML windows 8 app? how to inject RTF file to RichTextBlock in c#/xaml Windows store app How to print the contents of a TextBox in C#/XAML windows 8 app Applying Windows 8 Theme Dashboard to my Website designed in ASP.NET

Updated on June 25, 2022

Comments

  • Farhan Ghumra
    Farhan Ghumra almost 2 years

    in my app there is gridview of my custom class. I am using custom data template and values are bound from SQLite. Now when user launch the app, the certain items (NOT SINGLE) should be pre-selected in gridview/listview. Gridview/listview allows multiple selection. How can I achieve this with SelectedItem property ?

    UPDATE : I have followed this, it doesn't work for me. Returns 0 selections.

    UPDATE 2 : I have posted the code

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        using (var db = new SQLite.SQLiteConnection(dbpath))
        {
            lvTags.ItemsSource = db.Table<Database.Tag>();  //lvTags is listview
    
            if (MyList.Count > 0) //MyList is the static list of class "Database.Tag"
            {
                foreach (var item in MyList)
                    foreach (var lvitem in lvTags.Items)
                        if (lvitem.Equals(item))
                            lvTags.SelectedItems.Add(lvitem);
            }
        }
    }
    

    UPDATE 3:

    public override bool Equals(object obj)
    {
        Tag tag = obj as Tag;
        if (this.TagID == tag.TagID && this.TagName == tag.TagName)
            return true;
        else
            return false;
    }
    
  • Martin Suchan
    Martin Suchan over 11 years
    +1 for this, although this collection is readonly, cannot be databound and you have to populate it manually with pre-selected items.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    I am not using individual ListBoxItem (or GridViewItem). I am binding items source directly from SQLite's Query<T>() method.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    But how can I data bind it with manually pre-selected items ? I am having just SelectedValuePath from SQLite database.
  • Mamta D
    Mamta D over 11 years
    Updated my answer based on your comment.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    Thanks, but I am not using MVVM, mine app is simple. Can you please give me simple demo app, that contain several items in gridview and on app launched some will be selected.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    protected override void OnNavigatedTo(NavigationEventArgs e) { foreach (var item in MyList) //MyList is the list of my custom class having integer and string property. { //It contains the object which will be preselected in listview. MyListView.SelectedItems.Add(item); } } I tried this, it is not working.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    I also tried this
  • Filip Skakun
    Filip Skakun over 11 years
    Try sharing more of your code including XAML, data context, ItemsSource binding etc. in your original question.
  • Filip Skakun
    Filip Skakun over 11 years
    Perhaps Database.Tag from one of your list never equals any Database.Tag in the other list. You should possibly use a different type for your item view models than whatever you get from the database.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    the objects are similar, at both side values are same at if ((Database.Tag)lvitem == item)
  • Filip Skakun
    Filip Skakun over 11 years
    Similar != same. Have you implemented Equals operators for that type?
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    It returns false. Please suggest me some solution.
  • Filip Skakun
    Filip Skakun over 11 years
    override Equals to compare properties that indicate the items are the same - either some ID or all properties.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    I have override the Equals() (see Update 3 in question). lvTags.SelectedItems is having the entities but the list view doesn't show them selected.
  • Filip Skakun
    Filip Skakun over 11 years
    Is SelectedItems.Add() getting called?
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    yes, lvTags.SelectedItems.Add(lvitem) is called and lvTags.SelectedItems.Count is also greater than zero i.e. it is the same count value as MyList.Count. I suggest you to give me any sample project of that. I will be much thankful to you.
  • Filip Skakun
    Filip Skakun over 11 years
    Sorry, I'm a bit lost in this. I think you would need to rework your code to get the items as view model items and work on the list tailored for your view instead of relying directly on objects coming from db.Table<Database.Tag>(). Perhaps the items you are trying to add to SelectedItems aren't the same items that are assigned to ItemsSource.
  • Farhan Ghumra
    Farhan Ghumra over 11 years
    That's why I am telling you, please give me sample project, explaining the scenario which I want. Please I need that feature for my project.
  • Rahul Saksule
    Rahul Saksule almost 11 years
    I did same but not working in my case, I don't know why? What I am actually doing is selecting some items from GridView and then go back to previous page and then return on previous page, so items previously selected should be selected, which is not happening. Will You please help me?