WPF ListView SelectedItem is null

纵然是瞬间 提交于 2019-11-27 15:05:10

It's very easy, just handle Click event on your checkbox:

private void CheckBox_Click(object sender, RoutedEventArgs e) {
    var cb = sender as CheckBox;
    var item = cb.DataContext;
    myListView.SelectedItem = item;
}
Amsakanna

You have to parse your visual tree to get the index of the checkbox that is checked and select that particular listbox item in your code whenever some checkbox is checked

You may also be interested in

How to get checked items in a WPF ListBox?

and

http://goalbook.wordpress.com/2009/09/05/wpf-checkedlist-control/

Veer suggested parsing the visual tree to get the checkbox. The things is I already had the checkbox. What I needed was the listviewitem that held the checkbox. After further research this blog post pointed me in the right direction. Here is the code to get the listviewitem of the row that the checkbox was clicked:

        private void chkbox_Checked(object sender, RoutedEventArgs e)
    {
        DependencyObject dep = e.OriginalSource as DependencyObject;
        while ((dep != null) && !(dep is ListViewItem))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep != null)
        {
            IMyViewModel vm = DataContext as IMyViewModel;
            vm.SelectedThing = (MyListItemViewModel)lst.ItemContainerGenerator.ItemFromContainer(dep);
            vm.DoSomethingCommand.Execute(e.RoutedEvent.Name.ToLower());
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!