Hello,
This is actually a data binding problem in an asynchronous task.
Please refer to the following key code snippets of transforming an icon in an asynchronous task.
For model, since the program needs to be displayed in time after changing the icon, it is necessary to implement the INotifyPropertyChanged interface in the Model Class.
public class Item : INotifyPropertyChanged
{
public string Name { get; set; }
private string iconSource;
public string IconSource
{
get => iconSource;
set
{
if (iconSource != value)
{
iconSource = value;
OnPropertyChanged(); // reports this property
}
}
}
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
public event PropertyChangedEventHandler PropertyChanged;
}
For ViewModel:
public TestViewModel()
{
Items = new ObservableCollection<Item>();
ChangeCommand = new Command((x) => ChangeItem(x));
Items.Add(new Item { IconSource= "dotnet_bot.png",Name="test" });
Items.Add(new Item { IconSource = "dotnet_bot.png", Name = "test" });
Items.Add(new Item { IconSource = "dotnet_bot.png", Name = "test" });
Items.Add(new Item { IconSource = "dotnet_bot.png", Name = "test" });
}
public ICommand ChangeCommand { get; private set; }
private async void ChangeItem(object o)
{
Item item = o as Item;
if(item != null && Items.Contains(item)) {
item.IconSource = "test.png";
await Task.Delay(1000); //Simulate an asynchronous operation on data
item.IconSource = "finish.png";
}
}
For Xaml, in the CollectionView, you need to use relative binding to bind the button in the CollectionView to the Command that changes the icon.
<CollectionView ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<HorizontalStackLayout>
<Image Source="{Binding IconSource}"/>
<Label Text="{Binding Name}"/>
<Button Text="Delete" Command="{Binding Source={RelativeSource AncestorType={x:Type vm:TestViewModel}}, Path=ChangeCommand}" CommandParameter="{Binding .}"/>
</HorizontalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Use animation to transit from one status to another.
This is not feasible. Because the Image control is in the DataTemplate, it could not be operated in ViewModel.
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.