Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I looked at some of what's going on in ListView under the hood and think this is probably the best approach.</p> <pre><code>void listView_ItemCreated(object sender, ListViewItemEventArgs e) { // exit if we have already selected an item; This is mainly helpful for // postbacks, and will also serve to stop processing once we've found our // key; Optionally we could remove the ItemCreated event from the ListView // here instead of just returning. if ( listView.SelectedIndex &gt; -1 ) return; ListViewDataItem item = e.Item as ListViewDataItem; // check to see if the item is the one we want to select (arbitrary) just return true if you want it selected if (DoSelectDataItem(item)==true) { // setting the SelectedIndex is all we really need to do unless // we want to change the template the item will use to render; listView.SelectedIndex = item.DisplayIndex; if ( listView.SelectedItemTemplate != null ) { // Unfortunately ListView has already a selected a template to use; // so clear that out e.Item.Controls.Clear(); // intantiate the SelectedItemTemplate in our item; // ListView will DataBind it for us later after ItemCreated has finished! listView.SelectedItemTemplate.InstantiateIn(e.Item); } } } bool DoSelectDataItem(ListViewDataItem item) { return item.DisplayIndex == 0; // selects the first item in the list (this is just an example after all; keeping it simple :D ) } </code></pre> <p><strong>NOTES</strong></p> <ul> <li>ListView selects the template an item will use after it's DataBinding event fires. So if the SelectedIndex is set before then, no more work is necessary</li> <li>Setting the SelectedIndex anywhere after DataBinding works, you just don't get the SelectedItemTemplate. For that you have either rebind the data; or reinstantiate the SelectedItemTemplate on the ListViewItem. <em>be sure to clear the ListViewItem.Controls collection first!</em></li> </ul> <p><strong>UPDATE</strong> I have removed most of my original solution, since this should work better and for more cases.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload