Tono Nam
Tono Nam

Reputation: 36080

select item in System.Windows.Controls.ListView compared to System.Windows.Forms.ListView

In windows forms it is easy to select an item from a listview as:

myListView.items[index].selected = True;

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.

Upvotes: 0

Views: 1804

Answers (1)

brunnerh
brunnerh

Reputation: 185445

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]);

Upvotes: 4

Related Questions