Search code examples
c#wpfbuttonlistboxlistboxitem

How I can get access to a button / label from a ListBoxItem with just its databinding class?


I currently have a class object that is bound to a listboxitem. Before I used to get the other objects inside the ListBoxItem by clicking a button and accessing its parent, but now I need to gather the objects without clicking the buttons or labels, just by its class.

I've tried to gather the ListBoxItem with its index and its class binding, but both of them is giving me a null value:

ObservableCollection<ClassBinding> classList = new ObservableCollection<ClassBinding>();
... adding items here to the collection;
listBox.ItemsSource = classList;
ListBoxItem lbi = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(index);

Is there another way to access the listboxitem to later gather the other objects by using the function FindName(...)?

Debug:

TextBlock delay = lbi.FindName("lblDelay") as TextBlock;

Error:

Output: Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll

Solution

  • In order to find another solution/idea for this I came up with the INotifyPropertyChanged that can be added inside the classes, so there's no need to remove the ItemsSource from the list box, just hook the items source at the load of the program and then you can change the data inside the collection.

    I used the code from here: INotifyPropertyChanged and ObservableCollection WPF

    I didn't need to access the text blocks, just hooked some bindings to the objects and was able to do UI changes from just changing the values of the classes.