I want to dynamically add new flip view item in UWP. So that I can add infinite items to my flip view. For example, to fetch hot news and show them one by one in flip view.
I find some similar code from Internet and modify it a little. Below is the xaml code and cs code behind. As you can see, I want to use FlipView_SelectionChanged() to dynamic add new flip view item but failed. I expect to add new flip view item with text content like Name new 3, Name new 4...
XAML:
<Grid Name="grid">
<FlipView Name="flipView" ItemsSource="{Binding ModelItems}">
<FlipView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" FontSize="60" />
</StackPanel>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</Grid>
C#:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
flipView.SelectionChanged += FlipView_SelectionChanged;
}
private void FlipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Debug.WriteLine("flipview selection changed...index = " + flipView.SelectedIndex);
BaseViewModel bv = new BaseViewModel();
bv.ModelItems.Add(new BaseViewModelItem() { Name = "Name new " + flipView.SelectedIndex });
//grid.DataContext = bv;
Debug.WriteLine("flipview selection changed...count = " + bv.ModelItems.Count);
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
grid.DataContext = new BaseViewModel();
}
public class BaseViewModelItem
{
public string Name { get; set; }
}
public class BaseViewModel
{
public ObservableCollection<BaseViewModelItem> ModelItems { get; set; }
public BaseViewModel()
{
ModelItems = new ObservableCollection<BaseViewModelItem>();
ModelItems.Add(new BaseViewModelItem() { Name = "Name 1" });
ModelItems.Add(new BaseViewModelItem() { Name = "Name 2" });
ModelItems.Add(new BaseViewModelItem() { Name = "Name 3" });
}
}
}
I have modified the code that you have shared. I suggest you to use data binding instead of FlipView_SelectionChanged(), whenever item added to the ModelItems it update the element which it is bounded. I hope this will be helpful.
Logical Part code