I try to add strings that are in a string array to an ObservableCollection.
The way i do it is:
In my constructor i instantiate the collection and add the eventhandler to call my method that adds the strings from the array to the list:
public CLoggerViewModel()
{
this._currenLogContent = new ObservableCollection<string>();
this._memoryAppender.LogContentChanged += new LoggingEventHandler(OnLogContentChanged);
}
In the eventhandler i want to iterate through the string array and add each string to the collection:
public void OnLogContentChanged(object sender, LoggingEventArgs e)
{
string[] tmpString = { "A", "B", "C", "D" };
foreach (string s in tmpString)
{
_currenLogContent.Add(s);
}
}
In my Argument
e.LogEntries
which holds my string array i have always all the strings that i expect. For simplicity/test i dont use the array that i get from my argument and instantiate it with A,B,C,D , since i was asked to change it in way that it can be verified here.
My problem is that always just the first string of the array will be added to my ObservableCollection. Once the first string is added it seems that my foreach iteration gets terminated.
EDIT:
In my WPF XAML file if have the following list box where my ObservableCollection is bound to:
<ListBox Name="listViewLog" ItemsSource="{Binding LoggerViewModel.CurrentLogContent,UpdateSourceTrigger=PropertyChanged}" Margin="0,0,-248,-377" Grid.ColumnSpan="2" RenderTransformOrigin="0.586,0.51" Height="367" VerticalAlignment="Bottom" />
If i remove the listbox with the binding to my Observablecollection it iterates through the foreachloop. So the listbox or the binding from the listbox to my collection is causing the stop of the iteration. I already tried to use all the UpdateSourceTrigger options (Default,Explicit,LostFocus,PropertyChanged). But in all cases it stops the iteration after the first round.
Is there anything else that i have to set in the ListBox properties to avoid stopping to add strings to the Observablecollection?
EDIT:
The only solution i found that works for me is to Wrap the strings that i want to add to the collection in a separate class and adding the objects to the list. In this case it does not break my foreach loop if i add objects to the list.
public void OnLogContentChanged(object sender, LoggingEventArgs e)
{
string[] tmpString = { "A", "B", "C", "D" };
foreach (string s in tmpString)
{
this.LogEntries.Add(new CLogEntry(s));
}
}
CLogEntry is just a Wrapper that exposes a single string.
With this workaround it works, but still, i cant understand why it does not work if i "directly" add a string to the Observablecollection.