开发者

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

开发者 https://www.devze.com 2023-03-27 12:01 出处:网络
In windows forms it is easy to select an item from a listview as: myListView.items[index].selected = True;

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

精彩评论

暂无评论...
验证码 换一张
取 消