I'm facing an issue with ObservableCollection CollectionChanged event. I have a MainWindow.xaml file that contains a listView and I use the code behing to focus on my new added (or modified) elements in my listView.
<ListView x:Name="recordListView" Grid.Row="0" Grid.Column="0" Height="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Visible" Margin="20,20,20,10"
AlternationCount="2"
ItemsSource="{Binding Path=SessionRecords}" FontSize="14" >
…
</ListView>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var mainWindowViewModel = (MainWindowViewModel)DataContext;
mainWindowViewModel.SessionRecords.CollectionChanged += SessionRecords_CollectionChanged;
}
private void SessionRecords_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.NewItems?[0] != null)
{
recordListView.ScrollIntoView(e.NewItems[0]);
}
}
}
You probably notice I use a ViewModel.
public partial class MainWindowViewModel : BaseViewModel
{
private ObservableCollection<Record> sessionRecords;
public ObservableCollection<Record> SessionRecords
{
get
{
if (sessionRecords == null)
{
sessionRecords = new ObservableCollection<Record>();
sessionRecords.CollectionChanged += new NotifyCollectionChangedEventHandler(SessionRecordsCollectionChangedMethod);
}
return sessionRecords;
}
}
}
On runtime when I add a new item to my observable collection the collection changed event is raised before the item appears on the screen. How can I make sure the event is raised after the element appears in my screen? Or what should I do to make sure my grid always scroll and focus en new added or existing modified item? With MVVM or not, I don't care.
ecan't be null, soe?.is redundant. There is alsoe.Actionproperty that you might be interested in. - vasily.sib