I am attempting to implement a Carousel View in Xamarin.Forms where the user can add items to the carousel by pressing a button. I can initially load some items, but when I try to add another item at run time, the change is not reflected in the app. During debugging, I can confirm that the ObservableCollection that Itemssource is bound to does have an item added to it, but the UI does not reflect that added item.
Here is my ConfigurationView.xaml:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:JoyHost_GUI.Views;assembly=JoyHost_GUI"
x:Class="JoyHost_GUI.Views.ConfigurationView">
<ContentView.Content>
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding ConfigName}" />
<Button Text="+ Add Channel" Command="{Binding AddChannelCommand}" />
</StackLayout>
<CarouselView ItemsSource="{Binding Channels}"
IndicatorView="indicatorView"
IsSwipeEnabled="True"
Loop="False"
VerticalOptions="StartAndExpand"
x:Name="ChannelsCarousel">
<CarouselView.ItemTemplate>
<DataTemplate>
<views:ChannelView BindingContext="{Binding .}"/>
</DataTemplate>
</CarouselView.ItemTemplate>
<CarouselView.ItemsLayout>
<LinearItemsLayout Orientation="Horizontal" ItemSpacing="0" SnapPointsType="MandatorySingle" SnapPointsAlignment="Center" />
</CarouselView.ItemsLayout>
</CarouselView>
<IndicatorView x:Name="indicatorView"
IndicatorColor="LightGray"
SelectedIndicatorColor="Blue"
HorizontalOptions="Center"
Margin="0,0,0,10"/>
</StackLayout>
</ContentView.Content>
</ContentView>
Here is the code-behind:
namespace JoyHost_GUI.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ConfigurationView : ContentView
{
ConfigurationViewModel configurationViewModel;
public ConfigurationView()
{
InitializeComponent();
configurationViewModel = new ConfigurationViewModel();
BindingContext = configurationViewModel;
}
}
}
And here is the ViewModel:
namespace JoyHost_GUI.ViewModels
{
public class ConfigurationViewModel : BaseNotifyPropertyChanged
{
public ObservableCollection<ChannelModel> Channels { get; }
public ICommand AddChannelCommand { get; }
private string _configName;
public ConfigurationViewModel()
{
Channels = new ObservableCollection<ChannelModel>();
AddChannelCommand = new Command(() =>
{
Channels.Add(new ChannelModel());
});
}
public string ConfigName
{
get => _configName;
set
{
_configName = value;
OnPropertyChanged();
}
}
public void AddChannels(IEnumerable channels)
{
foreach(ChannelModel channel in channels)
{
Channels.Add(channel);
}
}
}
}
In short, after the AddChannelCommand is executed, the underlying Channels structure is updated, but not the GUI of the app.