ListBox.ItemContainerGenerator.ContainerFromItem () returns null to the new item added to the list

This is my first post, so I hope you could help me with my issue regarding WPF.

I have a list associated with an ObservableCollection:

public ObservableCollection<DeviceSetting> DeviceSettings { get { return _deviceSettings; } set { _deviceSettings = value; } } <ListBox ItemTemplate="{StaticResource IPItemTemplate}" Name="listBoxAddresses" SelectionMode="Extended" ItemsSource="{Binding Path=TestSetting.DeviceSettings, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" ItemContainerStyle="{StaticResource ContainerStyle}" /> 

The situation is here, I would like to know if a new item has been added to the list, so I created the CollectionChanged event:

 TestSetting.DeviceSettings.CollectionChanged += mListBox_CollectionChanged; private void mListBox_CollectionChanged(object sender,NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { for (int i = 0; i < TestSetting.DeviceSettings.Count; i++){ ListBoxItem myListBoxItem = (ListBoxItem)(listBoxAddresses.ItemContainerGenerator.ContainerFromItem(listBoxAddresses.Items[i])); if (!TestSetting.DeviceSettings[i].IsNetwork && DeviceDiscovery.IsSelected) myListBoxItem.IsEnabled = false; else if (TestSetting.DeviceSettings[i].IsNetwork && !DeviceDiscovery.IsSelected) myListBoxItem.IsEnabled = false; else myListBoxItem.IsEnabled = true; } } 

But there is a problem in this statement:

 ListBoxItem myListBoxItem = (ListBoxItem)(listBoxAddresses.ItemContainerGenerator.ContainerFromItem(listBoxAddresses.Items[i])); 

Every time I added a new element, the statement above always returns null, so the new element that was added was not checked if it is included or not. Is there any way for this statement to return the correct ListBoxItem that I need?

+6
source share
3 answers

You handle the base collections of CollectionChanged . Just because the collection has been changed does not mean that the item has been displayed, and the UIElement ready.

Register the ItemsGenerator.StatusChanged event, which should ensure that the UIElement ready.

+7
source

I did not find the ItemsGenerator.StatusChanged event on Windows Phone, but it worked with listBoxAddresses.LayoutUpdated

I also had to make sure myListBoxItem is different from zero.

0
source

If you are loading a control and trying to access ...

 ItemContainerGenerator.ContainerFromItem(object here) 

I was able to work around the problem by executing it in my ListBox.Loaded event. for instance

 SourceColumnListBox.Loaded += SourceColumnListBox_Loaded; 

Then inside the SourceColumnListBox_Loaded handler, everything works fine.

0
source

Source: https://habr.com/ru/post/900996/


All Articles