我正在尝试在 Xamarin.Forms 中实现轮播视图,用户可以通过按下按钮将项目添加到轮播中。我最初可以加载一些项目,但是当我尝试在运行时添加另一个项目时,更改不会反映在应用程序中。在调试期间,我可以确认 Itemssource 绑定的 ObservableCollection 确实添加了一个项目,但 UI 没有反映该添加的项目。
这是我的 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>
下面是代码隐藏:
namespace JoyHost_GUI.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ConfigurationView : ContentView
{
ConfigurationViewModel configurationViewModel;
public ConfigurationView()
{
InitializeComponent();
configurationViewModel = new ConfigurationViewModel();
BindingContext = configurationViewModel;
}
}
}
这是 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);
}
}
}
}
简而言之,在 AddChannelCommand 执行后,底层 Channels 结构被更新,而不是应用程序的 GUI。