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?
source share