Reputation: 2497
I've set up a Picker
so that each item is shown with a random number appended to it (via a converter). I've also added a button that raises the PropertyChanged
event on the list, so that the items are shown with a new set of random numbers. However, even though the PropertyChanged
event is being raised, the items don't appear to be updated.
Here's the XAML layout with the Picker
and Button
:
<StackLayout>
<Picker
ItemsSource="{Binding MyList}"
ItemDisplayBinding="{Binding ., Converter={StaticResource MyConverter}}"
/>
<Button
Command="{Binding RefreshCommand}"
Text="Refresh"
/>
</StackLayout>
Here's the view model, which contains MyList
and RefreshCommand
. The RefreshCommand
raises the PropertyChanged
event for MyList
(via ViewModelBase
, which is part of the MVVM Light Toolkit):
public class MainViewModel : ViewModelBase
{
private ObservableCollection<MyEnum> _myList;
public ObservableCollection<MyEnum> MyList
{
get => _myList;
set => Set(ref _myList, value);
}
public ICommand RefreshCommand =>
new RelayCommand(() => RaisePropertyChanged(nameof(MyList)));
}
public enum MyEnum
{
One, Two, Three, Four, Five
}
Here's the converter, which appends a random number to the given value:
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var random = new Random();
return $"{value} {random.Next(100)}";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Things work when the page is first displayed: each item in MyList
is shown with a random number appended to it. However, when I click on the Refresh button, which raises the PropertyChanged
event for MyList
(I verified this), the items in the Picker
are not re-evaluated. I expected new random numbers to show up but it's the same numbers as before (in other words, nothing happens).
Upvotes: 0
Views: 348
Reputation: 6643
You have to reset the Picker's items source like:
RefreshCommand = new Command( async () =>
{
ObservableCollection<MyEnum> list = MyList;
MyList = null;
await Task.Delay(10);
MyList = list;
});
It will trigger the converter again to refreh the random value.
Upvotes: 1