WPF - How do I get an object that is bound to a ListBoxItem back

穿精又带淫゛_ 提交于 2019-12-05 07:36:41

Each ListBoxItem will have the corresponding item in the data bound collection as DataContext. And each control in the ListBoxItem.ItemTemplate will inherint the DataContext. To get the object behind the clicked button you can do the following in the click event handler:

MyClass item = (MyClass)(sender as Button).DataContext;

To have changes in the data source automatically updated to the list box, you can use an ObservableCollection.

To Question 2: Use an ObservableCollection. This implements INotifyCollectionChanged so items will be added and removed as the collection changes.

To Question 1: Cast the sender as a button and use it's DataContext. This will be the item it's bound to. If you also need to get the ListBoxItem itself, you can you the VisualTreeHelper.GetParent() to search up the tree.

Use ObservableCollection to see instant automatic changes

Get the SelectedItem using the DataContext

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    var btn = sender as Button; 
    myListBox.SelectedItem = btn.DataContext; 
}

You should have a SelectedItem property in your viewmodel bound to the listbox's selectedItem. Delete that particular item from your ObservableCollection. Your listbox will reflect changes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!