In windows forms it is easy to select an item from a listview as:
myListView.items[index].selected = True;
开发者_StackOverflow中文版
on wpf it is not the same. I am binding a List to myListView. as a result I am not able to cast a someClass object to ListViewItem in order to call the IsSelected method. In other words this will not work:
foreach (ListViewItem item in listView1.Items)
{
item.IsSelected = true;
}
because item cannot be treated as a ListViewItem. How can I select items then? I am able to select all the items though by calling myListView.selectAll() method.
how can I select a single object on my listview programmaticaly.
In most cases you are supposed to bind the selection to some property on your object. e.g.
<ListView Name="_lv" ItemsSource="{Binding Data}">
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
class MyClass : INotifyPropertyChanged
{
private bool _IsSelected = false;
public bool IsSelected
{
get { return _IsSelected; }
set
{
if (_IsSelected != value)
{
_IsSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
//...
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Then setting that property in code will select the item:
foreach (MyClass item in Data)
{
item.IsSelected = true;
}
You also can manipulate the SelectedItems
collection:
_lv.SelectedItems.Clear();
_lv.SelectedItems.Add(Data[4]);
精彩评论