Reputation: 3
I have a simple problem. I have a listView and it's datasource is a List. It is not updated immediately, but only when the codeflow ends. What's the problem?
Below xaml:
<ListView x:Name="listView" ItemsSource="{Binding InfoBancaDatiAttuale}" HorizontalAlignment="Left" Height="130" Margin="212,34,0,0" VerticalAlignment="Top" Width="310">
<ListView.View>
<GridView>
<GridViewColumn/>
</GridView>
</ListView.View>
</ListView>
Below xaml.cs:
private List<string> _infoBancaDatiAttuale;
public List<string> InfoBancaDatiAttuale
{
get { return _infoBancaDatiAttuale; }
set
{
_infoBancaDatiAttuale = value;
onPropertyChanged("InfoBancaDatiAttuale");
}
}
private void AddToListAndNotify(List<string> list, string value, string propertyNotify)
{
List<string> tempList = list;
tempList.Add(value);
InfoBancaDatiAttuale = tempList;
}
In xaml.cs file I have also a procedure that perform instruction and should refresh UI. Percentage refresh a ProgressBar and I see that is update instantanely but InfoBancaDatiAttuale not refresh until the method finish.
public void performInstruction() {
Percentage = (int)((1 * 100) / 11);
AddToListAndNotify(InfoBancaDatiAttuale, "1) Eseguo login", "InfoBancaDatiAttuale");
//...instruction
Percentage = (int)((2 * 100) / 11);
AddToListAndNotify(InfoBancaDatiAttuale, "2) Another operation", "InfoBancaDatiAttuale");
//...instruction
Percentage = (int)((3 * 100) / 11);
AddToListAndNotify(InfoBancaDatiAttuale, "3) Another operation", "InfoBancaDatiAttuale");
}
What's the problem?
Upvotes: 0
Views: 39
Reputation: 20461
Your issue is nothing to do with INotifyPropertyChanged
, INotifyCollectionChanged
and you dont need to use an ObservableCollection
(although it would be slightly more efficient)
Your problem is that your performInstruction
Method is running on the UI Thread and the Dispatcher is unable to update the user interface until the method has completed, which is why nothing happens until the method has completed.
What you could to is:
public void performInstruction() {
Task.Run(() => {
Percentage = (int)((1 * 100) / 11);
AddToListAndNotify(InfoBancaDatiAttuale, "1) Eseguo login",
"InfoBancaDatiAttuale");
//...instruction
Percentage = (int)((2 * 100) / 11);
AddToListAndNotify(InfoBancaDatiAttuale, "2) Another operation",
"InfoBancaDatiAttuale");
//...instruction
Percentage = (int)((3 * 100) / 11);
AddToListAndNotify(InfoBancaDatiAttuale, "3) Another operation",
"InfoBancaDatiAttuale");
};
}
And before anyone suggests that you need to marshal the property changes up to the dispatcher thread, I can assure you that it isnt necessary.
Upvotes: 1
Reputation: 7277
You should use ObservableCollection<string>
. It will fire the CollectionChanged
event of the INotifyCollectionChanged
interface whenever an item is added to or removed from the collection.
private ObservableCollection<string> _items;
public ObservableCollection<string> Items => _items ?? (_items = new ObservableCollection<string>());
Upvotes: 0